<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xml:base="https://web-engineering.info"  xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
 <title>web-engineering.info - C/C++</title>
 <link>https://web-engineering.info/taxonomy/term/43</link>
 <description></description>
 <language>en</language>
<item>
 <title>WoT with Arduino for Beginners: Part 2 - Connecting to the Real World via Sensors</title>
 <link>https://web-engineering.info/node/61</link>
 <description>&lt;div class=&quot;field field-name-body field-type-text-with-summary field-label-hidden view-mode-rss&quot;&gt;&lt;div class=&quot;field-items&quot;&gt;&lt;div class=&quot;field-item even&quot; property=&quot;content:encoded&quot;&gt;&lt;p&gt;In this multi-part tutorial we show how to develop Arduino-based apps for the Web of Things (WoT). This second part shows how to read data with the help of analog or digitally controlled sensors. In the following parts of this tutorial, which will appear every 1-3 weeks, we discuss how to control actuators and how to connect them all together in a Web of Things (WoT) network. Using standard Web technologies, such as HTTP and Web Sockets, we can then access the data or provide commands to the WoT nodes. As a newbie, it is helpful if you already have some basic C/C++ programming knowledge and understanding of some Web standards and programming languages, such as HTML and JavaScript.&lt;/p&gt;

&lt;p&gt;Check the other parts of this tutorial series:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://web-engineering.info/node/60&quot;&gt;Part 1: Mastering the RGB LED&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;small&gt;&lt;strong&gt;Disclaimer:&lt;/strong&gt; working with electricity is dangerous. For this project we&#039;ll use 5V, which is safe for the human body under any environment conditions. However, the low voltage may be obtained from a mains connected power brick, and therefore we highly recommend you to take safety precautions and to use a trustful brand for the power supply. We cannot be held responsible for any caused damage! Do it at your own risk and/or ask help from an electronics engineer. In case you are using the USB connector from your PC to power the Arduino board, be aware that short-circuits which may occur on the Arduino board may also have a negative impact on your PC!&lt;/small&gt;&lt;/p&gt;

&lt;p style=&quot;margin-top:1em&quot;&gt;&lt;small&gt;&lt;strong&gt;Credits:&lt;/strong&gt; some of the images from this tutorial are created by using &lt;a href=&quot;http://fritzing.org/home/&quot;&gt;Fritzing&lt;/a&gt;, a nice electronics modeling tool for beginners.&lt;/small&gt;&lt;/p&gt;

&lt;h4&gt;&lt;strong&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/WoT-Tutorial-Part2.zip&quot;&gt;Download Source Code&lt;/a&gt;&lt;/strong&gt;&lt;/h4&gt;

&lt;h2&gt;What is a Sensor ?&lt;/h2&gt;

&lt;p&gt;A sensor is a device that is able to capture a quality (property) of the environment, within its detection radius, and provides, in some form, a quantity value representing the quantitative characteristics of that property. There are two main categories of sensors: electronic sensor or mechanical sensors.&lt;/p&gt;

&lt;p&gt;Examples of devices consisting of one or more sensors:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;&lt;em&gt;electronic sensors:&lt;/em&gt; digital thermometers, weather stations or alcohol level testers;&lt;/li&gt;
	&lt;li&gt;&lt;em&gt;mechanical sensors:&lt;/em&gt; water levels using balloons and graded bars, tire pressure testers found in gas stations, spring based pressure sensors found in some vices or force sensors found in manometer tools.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Usually, we also call sensor a collection of detectors, such as measuring temperature and humidity in the same time. A detector is an atomic sensor, able to measure one specific quality. Therefore, a sensor may consist of either one or more detectors.&lt;/p&gt;

&lt;p&gt;Further in this tutorial we only discuss about electronic sensors/detectors: their output is an electric signal, that can be captured and interpret as the quantity of the environment measured quality (property). We&#039;ll use Arduino UNO board as interface (or controller), but most of the other Arduino boards (Nano, Micro, MEGA2560, etc) works as well with the provided code examples, without any or with very minor changes.&lt;/p&gt;

&lt;h2&gt;Digital Sensors&lt;/h2&gt;

&lt;p&gt;A digital sensor is a sensor that uses a digital communication interface. Such an interface can be a standard one, such as &lt;a href=&quot;https://en.wikipedia.org/wiki/I%C2%B2C&quot;&gt;I2C&lt;/a&gt;, &lt;a href=&quot;https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus&quot;&gt;SPI&lt;/a&gt; or &lt;a href=&quot;https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter&quot;&gt;UART&lt;/a&gt;, but can also be a custom one, such as a stream of HIGH and LOW signals (also known as pulses), which are then interpreted as binary data. Custom digital interfaces may also refer to simply measuring a pulse for an amount of time and interpreting its length as the received information. Last but not least, some digital sensors are only providing a HIGH (or LOW) signal, when an event occurs, such as a intrusion detection sensor.&lt;/p&gt;

&lt;p&gt;In this tutorial we discuss the DHT11/DHT22 humidity and temperature sensor as well as the HC-SR04 distance measurement sensor, both using a custom digital interface.&lt;/p&gt;

&lt;h3&gt;Measure Temperature and Humidity with a DHT11/DHT22 Sensor&lt;/h3&gt;

&lt;p&gt;It is fairly simple to measure temperature and relative air humidity with the help of DHT11, DHT21 or DHT22 sensors. Each of those consists in fact of two detectors in a single package, and with a single 1-Wire custom digital communication interface. The main differences between these sensors are the measured ranges and their accuracy and resolution properties, as shown in the table &lt;a href=&quot;#table1&quot;&gt;Table 1&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;These sensors are fairly low priced, and in EU you can buy a DHT11 sensor for about 3EUR, a DHT21 for about 4EUR and a DHT22 for about 5EUR, postage included. The price can be cut in less than half when you are willing to order it online from China (e.g., by using &lt;a href=&quot;http://www.ebay.com/sch/i.html?_nkw=DHT11&quot;&gt;eBay&lt;/a&gt;), but be warned, the time to receive it in EU is usually from three to six weeks, sometimes even longer.&lt;/p&gt;

&lt;table id=&quot;table1&quot;&gt;
	&lt;caption&gt;Table 1: DHT11/DHT21/DHT22 Sensor Characteristics.&lt;/caption&gt;
	&lt;thead&gt;
		&lt;tr&gt;
			&lt;th&gt;&amp;nbsp;&lt;/th&gt;
			&lt;th&gt;DHT11 Temperature&lt;/th&gt;
			&lt;th&gt;DHT11 Air Humidity&lt;/th&gt;
			&lt;th&gt;DHT21/HM2301 Temperature&lt;/th&gt;
			&lt;th&gt;DHT21/HM2301 Air Humidity&lt;/th&gt;
			&lt;th&gt;DHT22/AM2302 Temperature&lt;/th&gt;
			&lt;th&gt;DHT22/AM2302 Air Humidity&lt;/th&gt;
		&lt;/tr&gt;
	&lt;/thead&gt;
	&lt;tbody&gt;
		&lt;tr&gt;
			&lt;td&gt;Range&lt;/td&gt;
			&lt;td&gt;[0, 50]°C&lt;/td&gt;
			&lt;td&gt;[20, 90]%&lt;/td&gt;
			&lt;td&gt;[-40, 80]°C&lt;/td&gt;
			&lt;td&gt;[0, 100]%&lt;/td&gt;
			&lt;td&gt;[-40, 125]°C&lt;/td&gt;
			&lt;td&gt;[0, 100]%&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Accuracy&lt;/td&gt;
			&lt;td&gt;±2°C&lt;/td&gt;
			&lt;td&gt;±5%&lt;/td&gt;
			&lt;td&gt;±1°C&lt;/td&gt;
			&lt;td&gt;±5%&lt;/td&gt;
			&lt;td&gt;±0.2°C&lt;/td&gt;
			&lt;td&gt;±2%&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Resolution&lt;/td&gt;
			&lt;td&gt;1°C&lt;/td&gt;
			&lt;td&gt;1%RH&lt;/td&gt;
			&lt;td&gt;0.1°C&lt;/td&gt;
			&lt;td&gt;0.1%RH&lt;/td&gt;
			&lt;td&gt;0.1°C&lt;/td&gt;
			&lt;td&gt;0.1%RH&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Operating voltage&lt;/td&gt;
			&lt;td&gt;[3.3, 5.5]V&lt;/td&gt;
			&lt;td&gt;[3.3, 5.5]V&lt;/td&gt;
			&lt;td&gt;[3.3, 6]V&lt;/td&gt;
			&lt;td&gt;[3.3, 6]V&lt;/td&gt;
			&lt;td&gt;[3.3, 6]V&lt;/td&gt;
			&lt;td&gt;[3.3, 6]V&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;Operating current&lt;/td&gt;
			&lt;td&gt;[1.2, 2]mA&lt;/td&gt;
			&lt;td&gt;[1.2, 2]mA&lt;/td&gt;
			&lt;td&gt;[1.3, 2.1]mA&lt;/td&gt;
			&lt;td&gt;[1.3, 2.1]mA&lt;/td&gt;
			&lt;td&gt;[1.3, 2.1]mA&lt;/td&gt;
			&lt;td&gt;[1.3, 2.1]mA&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&amp;nbsp;&lt;/td&gt;
			&lt;td colspan=&quot;2&quot; style=&quot;text-align:center; font-weight: bold;&quot;&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/DHT11.pdf&quot;&gt;Download datasheet&lt;/a&gt;&lt;/td&gt;
			&lt;td colspan=&quot;2&quot; style=&quot;text-align:center; font-weight: bold;&quot;&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/DHT21.pdf&quot;&gt;Download datasheet&lt;/a&gt;&lt;/td&gt;
			&lt;td colspan=&quot;2&quot; style=&quot;text-align:center; font-weight: bold;&quot;&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/DHT22.pdf&quot;&gt;Download datasheet&lt;/a&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;DHTxx sensor&amp;nbsp;may come with or without a breakout board, which allows not only to fix the sensor with a screw in a fixed place, but also usually have a LED to indicate that the sensor receives power, and most of them provides a PULL UP resistor, which otherwise you have to add between their DATA and VCC pins. A PULL UP resistor has usually a value between 2kΩ and 20kΩ (most common values are 4.7kΩ and 10kΩ), and it connects the corresponding data line to VCC, thus the line stays at VCC level as long there is no other activity from the micro-controller, to pull the data line to LOW. &lt;a href=&quot;#fig1&quot;&gt;Figure 1&lt;/a&gt; shows variations of DHT11 sensors and &lt;a href=&quot;#fig2&quot;&gt;Figure 2&lt;/a&gt; shows variations of DHT22 sensors, with or without a breakout board, as well as the pin-out (pins configuration).&lt;/p&gt;

&lt;figure id=&quot;fig1&quot;&gt;&lt;img alt=&quot;DHT11 Sensors&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/DHT11.png&quot; /&gt;
&lt;figcaption&gt;Figure 1: Variations of DHT11 Sensor.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig2&quot;&gt;&lt;img alt=&quot;DHT22 Sensors&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/DHT22.png&quot; /&gt;
&lt;figcaption&gt;Figure 2: Variations of DHT22 Sensor.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4&gt;Hardware Configuration&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;#fig3&quot;&gt;Figure 3&lt;/a&gt; shows how to connect a DHTxx sensor to an Arduino UNO board, and &lt;a href=&quot;#fig4&quot;&gt;Figure 4&lt;/a&gt; shows the electronics schematics. Notice the third pin of the sensor is not connected and all three variations of this sensor have the same pin-out.&lt;/p&gt;

&lt;figure id=&quot;fig3&quot;&gt;&lt;img alt=&quot;DHTxx Sensor Connected to an Arduino UNO Board&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-DHTxx-breadboard.png&quot; /&gt;
&lt;figcaption&gt;Figure 3: DHTxx Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig4&quot;&gt;&lt;img alt=&quot;Circuit Diagram for a DHTxx Sensor Connected to an Arduino UNO Board&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-DHTxx-schematics.png&quot; /&gt;
&lt;figcaption&gt;Figure 4: Circuit Diagram for a DHTxx Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;&lt;strong&gt;Note1:&lt;/strong&gt; if we use a DHTxx sensor without a breakout board that includes a PULL UP resistor, then we&#039;ll need to add a 10kΩ one between the VCC line and the DATA pin. If the PULL UP resistor is missing, the received data may be corrupted or may be no transmission.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note2:&lt;/strong&gt; in some diagrams, the VCC pin is also noted as VDD, but its meaning does not change.&lt;/p&gt;

&lt;h4&gt;Software Configuration&lt;/h4&gt;

&lt;p&gt;Its now the time to query the sensor and obtain temperature and humidity data. For this you&#039;ll need to add the DHTxx library to your Arduino IDE libraries collection. Download the DHTxx library from &lt;a href=&quot;https://github.com/dimircea/Arduino/tree/master/libraries/DHTxx&quot;&gt;github&lt;/a&gt; and copy the folder &lt;code&gt;DHTxx&lt;/code&gt; into your &lt;code&gt;libraries&lt;/code&gt; sub-folder of the Arduino installation folder. If the Arduino IDE was started before, you have now to close it and start it again.&lt;/p&gt;

&lt;p&gt;To &quot;load&quot; the DHTxx library into our Arduino sketch, we use the &lt;code&gt;#include&lt;/code&gt; directive. Then, we create an instance of the &lt;code&gt;Dht&lt;/code&gt; class (defined by the library), which takes care of the communication with the DHTxx sensor. Its constructor has two parameters: the pin number used to communicate with the sensor (the Arduino UNO digital pin 7 in our example), and the sensor type used (DHT11, DHT21 or DHT22), defined by the &lt;code&gt;Dht::TypeEL&lt;/code&gt; enumeration. While the DHTxx sensors are using almost the same data encoding during the communication, there are also slight differences, which require special attention inside the library code. Explicitly, one of &lt;code&gt;Dht::TypeEL::DHT11&lt;/code&gt;, &lt;code&gt;Dht::TypeEL::DHT21&lt;/code&gt; or &lt;code&gt;Dht::TypeEL::DHT22&lt;/code&gt; can be used as the second parameter of the constructor, depending on your sensor choice.&lt;/p&gt;

&lt;pre&gt;
&lt;strong&gt;#include &amp;lt;dhtxx.h&amp;gt;&lt;/strong&gt;
#define DHT_PIN 7

&lt;strong&gt;Dht dht(DHT_PIN, Dht::TypeEL::DHT22);&lt;/strong&gt;
&lt;/pre&gt;

&lt;p&gt;Since we like to see the read temperature and humidity values, we&#039;ll use the Arduino serial communication capabilities, in combination with the Arduino IDE serial monitor tool, which you can open by using the &quot;Tools &amp;gt; Serial Monitor&quot; menu. This additional code is only required for being able to visualize the information, but has nothing to do with the sensor, or sensor communication. The DHTxx sensor requires some initialization time, which is usually about two seconds, thus a delay of two seconds is added in the &lt;code&gt;setup&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;
void setup() {  
  Serial.begin(115200);
  delay(2000);
};
&lt;/pre&gt;

&lt;p&gt;Last, we use the &lt;code&gt;Dht::read&lt;/code&gt; method, to inquire temperature and humidity information from the sensor. A &lt;code&gt;Result&lt;/code&gt; structure is provided in return, and it has three properties: temperature, humidity and status, which should be &lt;code&gt;Dht::StatusEL::OK&lt;/code&gt; if no communication errors took place. We use a delay of five seconds between two readings.&lt;/p&gt;

&lt;pre&gt;
void loop() {
  &lt;strong&gt;Dht::Result result = dht.read();&lt;/strong&gt;
  if (result.status == Dht::StatusEL::OK) {
    Serial.print(&quot;Temperature: &quot;);
    Serial.println(result.temperature);
    Serial.print(&quot;Humidity: &quot;);
    Serial.println(result.humidity);
  } else if (result.status == Dht::StatusEL::CRC_ERROR) {
    Serial.println(&quot;CRC error! &quot;);
  } else {
    Serial.println(&quot;Timeout error! &quot;);
  }
  delay(5000);
};
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; DHTxx sensors can be read no faster than once every two seconds. Not following this rule results in no communication with the sensor or communication timeouts.&lt;/p&gt;

&lt;p&gt;If all went well, and you have used an DHT21 or DHT22 sensor, you should see the &lt;em&gt;Serial Monitor&lt;/em&gt; window showing information similar with &lt;a href=&quot;#fig5&quot;&gt;Figure 5&lt;/a&gt;. One can observe slight differences between readings (like 0.2°C between the temperature values), but that is just fine, and are the result of the sensor accuracy.&lt;/p&gt;

&lt;figure id=&quot;fig5&quot;&gt;&lt;img alt=&quot;Serial Monitor Showing DHTxx Sensor Readings&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Serial-Monitor-DHTxx.png&quot; /&gt;
&lt;figcaption&gt;Figure 5: Serial Monitor Showing DHTxx Sensor Readings.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;If you are interested in more information about the low level communication with the DHTxx sensor, then you should have a look at the DHTxx library code (files &lt;code&gt;DHTxx.h&lt;/code&gt; and &lt;code&gt;DHTxx.cpp&lt;/code&gt;) which contains detailed code comments. Also, check the information provided in the &lt;a href=&quot;https://github.com/dimircea/Arduino/tree/master/libraries/DHTxx&quot;&gt;DHTxx library github project page&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Measure Distance with HC-SR04 Ultrasonic Sensor&lt;/h3&gt;

&lt;p&gt;In multiple projects, measuring distance is an important aspect. Imagine a &quot;self-driving&quot; robot (or car) project, where detecting obstacles, thus measuring distance between the robot and any possible nearby objects, is one of the main tasks. Fortunately there is a easy and cheap way to achieve this, with the help of an ultrasonic based distance measurement sensor, such as HC-SR04, shown in &lt;a href=&quot;#fig6&quot;&gt;Figure 6&lt;/a&gt;. These sensors uses high frequency sound pulses (40KHz or more) and measure the time required by the sound to travel forth, and back if it is bounced by an nearby obstacle. Internally, a timeout is used to detect if an object exists or not in the sensor range (which for HC-SR04 is about 4m). In &lt;a href=&quot;#table2&quot;&gt;Table 2&lt;/a&gt; are shown the main characteristics of a HC-SR04 sensor.&lt;/p&gt;

&lt;p&gt;Variations of this sensor, using the UART communication interface (i.e., HC-SR03) can be found on the market. Usually, they are more expensive (the price is double or more), and the communication protocol required to communicate with such a sensor, especially RAM resources, are higher.&lt;/p&gt;

&lt;p&gt;HC-SR04 sensors are fairly low priced, and in EU you can buy one for as low as 3EUR including postage. If you are willing to wait up to six weeks, it is possible to buy such sensors from China (e.g., by using &lt;a href=&quot;http://www.ebay.com/sch/i.html?_nkw=hc-sr04&quot;&gt;eBay&lt;/a&gt;) for about 1EUR per piece, including postage.&lt;/p&gt;

&lt;table id=&quot;table2&quot;&gt;
	&lt;caption&gt;Table 2: HC-SR04 sensor characteristics.&lt;/caption&gt;
	&lt;thead&gt;
		&lt;tr&gt;
			&lt;th&gt;Range&lt;/th&gt;
			&lt;th&gt;Detection Angle&lt;/th&gt;
			&lt;th&gt;Accuracy&lt;/th&gt;
			&lt;th&gt;Resolution&lt;/th&gt;
			&lt;th&gt;Operating voltage&lt;/th&gt;
			&lt;th&gt;Operating current&lt;/th&gt;
		&lt;/tr&gt;
	&lt;/thead&gt;
	&lt;tbody&gt;
		&lt;tr&gt;
			&lt;td&gt;[2, 400]cm&lt;/td&gt;
			&lt;td&gt;30 degrees&lt;/td&gt;
			&lt;td&gt;3mm&lt;/td&gt;
			&lt;td&gt;1mm&lt;/td&gt;
			&lt;td&gt;[4.5, 5.5]V&lt;/td&gt;
			&lt;td&gt;[12, 18]mA&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td colspan=&quot;6&quot; style=&quot;text-align:center; font-weight: bold;&quot;&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/HC-SR04.pdf&quot;&gt;Download datasheet&lt;/a&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/tbody&gt;
&lt;/table&gt;

&lt;figure id=&quot;fig6&quot;&gt;&lt;img alt=&quot;HC-SR04 Sensor&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/HC-SR04.png&quot; /&gt;
&lt;figcaption&gt;Figure 6: HC-SR04 Sensor.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4&gt;Hardware Configuration&lt;/h4&gt;

&lt;p&gt;Connecting the Arduino board with the HC-SR04 sensor is really easy. First, you&#039;ll need to provide power to the VCC and GND pins. Second, chose two Arduino pins (use digital ones while the analog pins we need for other purposes) to be used in the communication with the sensor. One pin represents the &quot;trigger&quot;, informing the sensor that we like to read the distance, and the other one represents the output from sensor, also known as &quot;echo&quot;, providing a pulse of a specified length, mapped then to a distance value.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;#fig7&quot;&gt;Figure 7&lt;/a&gt; is shown how to wire the sensor to an Arduino UNO board, but the same apply to almost any other Arduino boards. &lt;a href=&quot;#fig8&quot;&gt;Figure 8&lt;/a&gt; shows the electrical diagram of the circuit.&lt;/p&gt;

&lt;figure id=&quot;fig7&quot;&gt;&lt;img alt=&quot;HC-SR04 Sensor Connected to an Arduino UNO Board&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-HCSR04-breadboard.png&quot; /&gt;
&lt;figcaption&gt;Figure 7: HC-SR04 Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig8&quot;&gt;&lt;img alt=&quot;Circuit Diagram of a HC-SR04Sensor Connected to an Arduino UNO Board&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-HCSR04-schematics.png&quot; /&gt;
&lt;figcaption&gt;Figure 8: Circuit Diagram of a HC-SR04Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4&gt;Software Configuration&lt;/h4&gt;

&lt;p&gt;Reading the distance with a HC-SR04 sensor requires to &lt;a href=&quot;https://github.com/dimircea/Arduino/tree/master/libraries/HCSR04&quot;&gt;download from github&lt;/a&gt; and import the HCSR04 into your Arduino IDE. For this, you&#039;ll need to copy the folder &lt;code&gt;HCSR04&lt;/code&gt; into your &lt;code&gt;libraries&lt;/code&gt; sub-folder of the Arduino installation folder. If the Arduino IDE was started before, you have now to close it and start it again.&lt;/p&gt;

&lt;p&gt;Use the #include directive to &quot;load&quot; the library into your Arduino sketch. Create an instance of the HCSR04 class, which takes care of the communication with the sensor. The constructor has two parameters: the pin number used to inform the sensor that we want to read the distance, known as the &lt;em&gt;trigger pin&lt;/em&gt; (the Arduino UNO digital pin 7 in our case), and the pin number used to read the sensor response, known as the &lt;em&gt;echo pin&lt;/em&gt; (the Arduino UNO digital pin 5 in our example).&lt;/p&gt;

&lt;pre&gt;
&lt;strong&gt;#include &amp;lt;HCSR04.h&amp;gt;&lt;/strong&gt;
#define TRIGGER_PIN 6
#define ECHO_PIN 5

&lt;strong&gt;HCSR04 hcsr04(TRIGGER_PIN, ECHO_PIN);&lt;/strong&gt;

&lt;/pre&gt;

&lt;p&gt;Since we want to test the sensor and check the distance it reads, we&#039;ll use the Arduino serial communication capabilities, in combination with the Arduino IDE serial monitor tool (use the &quot;Tools &amp;gt; Serial Monitor&quot; menu) to show the sensor readings. This additional code is only required for being able to visualize the information, but has nothing to do with the sensor, or sensor communication. The HC-SR04 sensor requires some initialization time, which is usually about one second, thus a delay of one second is added in the setup method.&lt;/p&gt;

&lt;pre&gt;
void setup() { 
  // Start serial communication, used to show 
  // sensor data in the Arduino serial monitor. 
  Serial.begin(115200); 
  // Wait for the HCSR04 sensor to settle. 
  // This usually needs about one second... 
  delay(1000); 
};&lt;/pre&gt;

&lt;p&gt;Use the &lt;code&gt;HC-Sr04::read&lt;/code&gt; method, to inquire distance measurement from the sensor. By default, the distance is measured in centimeters. If you need the distance in millimeters, meters or kilometers, use the &lt;code&gt;HCSR04::read(HCSR04::MetricsEL::xx)&lt;/code&gt; method instead. The value of the parameter can be one of: &lt;code&gt;HCSR04::MetricsEL::mm&lt;/code&gt;, &lt;code&gt;HCSR04::MetricsEL::cm&lt;/code&gt; (default), &lt;code&gt;HCSR04::MetricsEL::m&lt;/code&gt; or &lt;code&gt;HCSR04::MetricsEL::km&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;
void loop() {
  &lt;strong&gt;float distance = hcsr04.read();&lt;/strong&gt;
  if (distance &amp;gt; 0) {
    Serial.println(distance);
  } else {
    Serial.println(&quot;Error reading the sensor!&quot;);
  }
  // continuously read the sensor, ~10 times/s
  // Note: may be much less than ~10 times/s because reading
  // the sensor and checking the timeout may take up to 50ms
  delay(100);
};&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; while in theory you can make hundreds of readings per second with this sensor, the practice learn us that you can take under ten reliable readings every second second. This is due to Arduino capabilities but also to sensor internals, driven by another micro-controller.&lt;/p&gt;

&lt;p&gt;If all went well, you should see the &lt;em&gt;Serial Monitor&lt;/em&gt; window showing information similar with &lt;a href=&quot;#fig9&quot;&gt;Figure 9&lt;/a&gt;.&lt;/p&gt;

&lt;figure id=&quot;fig9&quot;&gt;&lt;img alt=&quot;Serial Monitor Showing HC-SR04 Sensor Readings&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Serial-Monitor-HCSR04.png&quot; /&gt;
&lt;figcaption&gt;Figure 9: Serial Monitor Showing HC-SR04 Sensor Readings.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;If we&#039;ve got your attention and you want to know more about how exactly the software communicates with the sensor and maps the detected pulse length into a distance value, please have a look at the library code which is commented in the smallest details.&lt;/p&gt;

&lt;h2&gt;Analog Sensors&lt;/h2&gt;

&lt;p&gt;Analog sensors provide information about the measured quality as a voltage level, or other equivalent form, e.g., resistance of current. Using various electronics laws and equations we can interpret these values as a quantity of the measured quality. Examples of such sensors are photo resistors, rain or soil moisture sensors, providing the information into the form of &quot;resistance&quot;. Other sensors, such as LM35 analog temperature sensor, directly provides a voltage level that can be translated into temperature value using a liner function.&lt;/p&gt;

&lt;h3&gt;Measure Temperature with LM35 Analog Sensor&lt;/h3&gt;

&lt;p&gt;LM35 sensor, shown in &lt;a href=&quot;#fig10&quot;&gt;Figure 10&lt;/a&gt;, is a very cheap way (it costs under one EUR for one piece) to measure the environment temperature, used in combination with any device that is able to read voltage in the millivolts range. That means, we can even use a multi-meter (a device able to measure voltage, resistance, current, etc) to measure the temperature, without the need of having an additional micro-controller. However, in this tutorial we show how to use an Arduino UNO to do the measurement. These sensors comes in multiple variations, from which the most known is LM35DZ. &lt;a href=&quot;#table3&quot;&gt;Table 3&lt;/a&gt; shows the most important characteristics. Other versions are different in ranges, accuracy or supply voltage values.&lt;/p&gt;

&lt;figure id=&quot;fig10&quot;&gt;&lt;img alt=&quot;LM35DZ Analog Sensor&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/LM35DZ.png&quot; /&gt;
&lt;figcaption&gt;Figure 10: LM35DZ Analog Sensor.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;table id=&quot;table3&quot;&gt;
	&lt;caption&gt;Table 2: LM35DZ Sensor Characteristics.&lt;/caption&gt;
	&lt;thead&gt;
		&lt;tr&gt;
			&lt;th&gt;Range&lt;/th&gt;
			&lt;th&gt;Accuracy&lt;/th&gt;
			&lt;th&gt;Resolution&lt;/th&gt;
			&lt;th&gt;Operating voltage&lt;/th&gt;
			&lt;th&gt;Operating current&lt;/th&gt;
		&lt;/tr&gt;
	&lt;/thead&gt;
	&lt;tbody&gt;
		&lt;tr&gt;
			&lt;td&gt;[-40, 110]°C&lt;/td&gt;
			&lt;td&gt;±0.25°C&lt;/td&gt;
			&lt;td&gt;0.2°C (= 2mV Output)&lt;/td&gt;
			&lt;td&gt;[-0.2, 35]V&lt;/td&gt;
			&lt;td&gt;[60, 100]µA&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td colspan=&quot;5&quot; style=&quot;text-align:center; font-weight: bold;&quot;&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/LM35DZ.pdf&quot;&gt;Download datasheet&lt;/a&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The linear function used to translate sensor output voltage in °C of temperature is: &lt;code&gt;f(x) = 100x&lt;/code&gt;, where &lt;code&gt;x&lt;/code&gt; is the sensor voltage output in volts and &lt;code&gt;f(x)&lt;/code&gt; is the temperature in °C. In other words, for every 1°C, the output voltage of this sensor is 10mV, e.g., 220mV output means a temperature value of 22°C.&lt;/p&gt;

&lt;h4&gt;Hardware Configuration&lt;/h4&gt;

&lt;p&gt;Connecting a LM35 sensor to Arduino UNO is very simple, as shown in &lt;a href=&quot;#fig11&quot;&gt;Figure 11&lt;/a&gt;. Just connect the VCC pin to 5V (obtained from Arduino UNO 5V pin), the GND pin to Arduino UNO ground and the output pin to one of the analog pins of the Arduino UNO board, annotated with A0...A5. In our example, we use A0. No additional components are required. &lt;a href=&quot;#fig12&quot;&gt;Figure 12&lt;/a&gt; shows the schematics of the circuit.&lt;/p&gt;

&lt;figure id=&quot;fig11&quot;&gt;&lt;img alt=&quot;LM35 Sensor Connected to an Arduino UNO Board.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-LM35-breadboard.png&quot; /&gt;
&lt;figcaption&gt;Figure 11: LM35 Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig12&quot;&gt;&lt;img alt=&quot;Circuit Diagram of a LM35 Sensor Connected to an Arduino UNO Board.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-LM35-schematics.png&quot; /&gt;
&lt;figcaption&gt;Figure 12: Circuit Diagram of a LM35 Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4&gt;Software Configuration&lt;/h4&gt;

&lt;p&gt;Ardunio UNO and most of the arduino boards comes with a feature known as ADC: Analog to Digital Converter. That is, connecting a voltage source to one of the ADC capable pins, we can measure the applied voltage value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; you should NOT try to measure voltages over VCC, so 5V in our case, with any ADC pin, because you&#039;ll burn your Arduino micro-controller. Also when using a 3.3V Arduino board, the maximum measurable voltage value with any ADC pin is 3.3V.&lt;/p&gt;

&lt;p&gt;First, we&#039;ll define the pin used to read the sensor. Analog pins can be refereed in an Arduino program with Ax (e.g., A0 or A3), and corresponds to the notation you see on your Arduino PCB board.&lt;/p&gt;

&lt;pre&gt;
#define LM35DZ_PIN A0
&lt;/pre&gt;

&lt;p&gt;We like to be able to see the sensor output, and for that we use the Arduino serial monitor feature. Some settle time is welcome for the LM35DZ sensor to adapt to the power supply and environment, and we allow it do do so for about one second (more is required if the temperature variation is larger than a few degrees).&lt;/p&gt;

&lt;pre&gt;
void setup() {
  Serial.begin(115200);
  delay(1000);
}
&lt;/pre&gt;

&lt;p&gt;Further, we can read the pin output by using the &lt;code&gt;analogRead&lt;/code&gt; method, which takes as parameter the used pin number, e.g., A0, expressed by LM35DZ_PIN. However, this method returns a number between 0 and 1023 for our Ardunio UNO. This is due to the fact that Arduino UNO ADC unit uses 10 bits to represent data, thus values from 0 to 1023. The question is now: how do we translate this number to the read voltage value?&lt;/p&gt;

&lt;p&gt;An ADC unit uses a reference voltage for measurements. By default, in most of the Arduino boards, including Arduino UNO, this is VCC (i.e., 5V). It means, that we have a range of [0, 5]V (or [GND, VCC]V) represented with integers in the range [0, 1023], therefore 1024 total values. In conclusion, one ADC unit is: &lt;code&gt;1U = 5 / 1024 ≈ 0.00488&lt;/code&gt;. For example, if &lt;code&gt;analogRead&lt;/code&gt; returns a value of 237, this represents &lt;code&gt;237 * 0.00488V ≈ 1.155V&lt;/code&gt;. Using this, we can now obtain the temperature value, knowing that our LM35DZ sensor has an output of 0.01V (10mV) for every °C: &lt;code&gt;temperature = adcUnits * 0.00488 * 100&lt;/code&gt;. Using Arduino code, that is:&lt;/p&gt;

&lt;pre&gt;
void loop() {
  uint16_t adcUnits = analogRead(LM35DZ_PIN);
  float temperature = adcUnits * 0.00488 * 100;
  Serial.print(&quot;Temperature: &quot;);
  Serial.println(temperature);
}
&lt;/pre&gt;

&lt;p&gt;Dealing with ADC units requires attention, and following the below two rules helps in obtaining stable readings:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;Read the datasheet and check the minimum interval between two ADC readings. For Arduino UNO the ADC clock works at 125KHz and one ADC conversion requires 13 clocks. Therefore, the reading can be done with a frequency of about 9600Hz, so about 9600 times per second, which means one reading every 100µS.&lt;/li&gt;
	&lt;li&gt;There are a multitude of factors affecting the ADC readings, such as temperature, magnetic waves, voltage stability and so on. Therefore is good to average a set of readings and use these as the &quot;absolute&quot; read value. For our example, it will be appropriate to average at least 10 samples before considering a temperature value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Following the above presented rules, we obtain the code below:&lt;/p&gt;

&lt;pre&gt;

void loop() {
  uint8_t i = 0;
  uint16_t adcUnits = 0;
  float temperature  = 0;
  for (i = 0; i &amp;lt; 9; i++) {
    adcUnits = analogRead(LM35DZ_PIN);
    temperature += adcUnits * 0.00488 * 100;
  }
  temperature /= 10;
  Serial.print(&quot;Temperature: &quot;);
  Serial.println(temperature);
  
  delay(5000);
}
&lt;/pre&gt;

&lt;p&gt;The new version of this code provides repeatable results within 0.2°C, while the first version can only provide repeatable results within 0.5°C. If all went fine, you should see the &lt;em&gt;Serial Monitor&lt;/em&gt; window showing information similar with &lt;a href=&quot;#fig13&quot;&gt;Figure 13&lt;/a&gt;&lt;/p&gt;

&lt;figure id=&quot;fig13&quot;&gt;&lt;img alt=&quot;Serial Monitor Showing LM35DZ Sensor Readings&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Serial-Monitor-LM35.png&quot; /&gt;
&lt;figcaption&gt;Figure 13: Serial Monitor Showing LM35DZ Sensor Readings.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h3&gt;Measure Light Intensity with a Photo Resistor&lt;/h3&gt;

&lt;p&gt;A photo-resistor is a special type of resistor which change its value based on the ambient light intensity. Usually, these resistors have specified values for &quot;complete dark&quot; and &quot;extreme light&quot;, and normally the datasheet presents a mapping function allowing to transform a resistance value into a luminous emittance value (measured in LUX).&lt;/p&gt;

&lt;p&gt;In this tutorial we discus about VT93N1 photo-resistor, fairly easy to use and with a low price of about 1EUR for one piece, EU postage included. Being a resistor, it can be mounted either way in a circuit. &lt;a href=&quot;#fig14&quot;&gt;Figure 14&lt;/a&gt; shows the pyhsical shape of a VT93N1 photo-resistor. In &lt;a href=&quot;#table4&quot;&gt; Table 4&lt;/a&gt; are shown the most important characteristics of the VT93N1 sensor.&lt;/p&gt;

&lt;table id=&quot;table4&quot;&gt;
	&lt;caption&gt;Table 4: VT93N1 Photo Resistor Characteristics.&lt;/caption&gt;
	&lt;thead&gt;
		&lt;tr&gt;
			&lt;th&gt;Range&lt;/th&gt;
			&lt;th&gt;Accuracy&lt;/th&gt;
			&lt;th&gt;Resolution&lt;/th&gt;
			&lt;th&gt;Adaptation time&lt;/th&gt;
			&lt;th&gt;Operating voltage&lt;/th&gt;
			&lt;th&gt;Max. power dissipation&lt;/th&gt;
		&lt;/tr&gt;
	&lt;/thead&gt;
	&lt;tbody&gt;
		&lt;tr&gt;
			&lt;td&gt;[12, 300]kΩ&lt;/td&gt;
			&lt;td&gt;±20%&lt;/td&gt;
			&lt;td&gt;1Ω&lt;/td&gt;
			&lt;td&gt;min. 5 seconds&lt;/td&gt;
			&lt;td&gt;[-60, 60]V&lt;/td&gt;
			&lt;td&gt;80mW&lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td colspan=&quot;6&quot; style=&quot;text-align:center; font-weight: bold;&quot;&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/VT93N1.pdf&quot;&gt;Download datasheet&lt;/a&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/tbody&gt;
&lt;/table&gt;

&lt;figure id=&quot;fig14&quot;&gt;&lt;img alt=&quot;VT93N1 Photo Resistor&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/VT93N1.png&quot; /&gt;
&lt;figcaption&gt;Figure 14: VT93N1 Photo Resistor.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;It is possible to measure a resistor, thus a photo-resistor too, by using various techniques such as:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;Use a constant current source, measure the dropout voltage over the resistor, then use Ohm&#039;s law to compute the resistance: &lt;code&gt;R = V / I&lt;/code&gt;, where R is the resistance in ohms we want to measure, V is the dropout voltage in volts across the resistor, and I is the applied constant current value in Amperes.&lt;/li&gt;
	&lt;li&gt;Use a voltage divider with another precision resistor, for which the resistance value is already known. Apply a known voltage across the end of the resistor network and measure the voltage drop across the resistor with the known value. The equation which applies is: &lt;code&gt;V_across_R2 = R2 * V_input / (R1 + R2)&lt;/code&gt;. We solve this for R1, that is the resistance we are interested in: &lt;code&gt;R1 = R2 * (V_input / V_across_R2 - 1)&lt;/code&gt;. Therefore, if we know the applied voltage to the circuit, the value of the fixed R2 resistor, and we measure the voltage drop across R2, we can easily compute the value of R1, measured in ohms.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In our case, since we don&#039;t have a constant current source, but we can use a resistor of a known value, the second method is used, as shown in &lt;a href=&quot;#fig15&quot;&gt;Figure 15&lt;/a&gt;, respectively &lt;a href=&quot;#fig16&quot;&gt;Figure 16&lt;/a&gt;. However, we&#039;ll use the Arduino UNO ADC capabilities to replace the voltmeter, as we learned earlier in this tutorial.&lt;/p&gt;

&lt;figure id=&quot;fig15&quot;&gt;&lt;img alt=&quot;Measure Resistance Using a Voltmeter.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-Resistor-Divider-breadboard.png&quot; /&gt;
&lt;figcaption&gt;Figure 15: Measure Resistance Using a Voltmeter.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig16&quot;&gt;&lt;img alt=&quot;Circuit Diagram for Measuring Resistance Using a Voltmeter.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-Resistor-Divider-schematics.png&quot; /&gt;
&lt;figcaption&gt;Figure 16: Circuit Diagram for Measuring Resistance Using a Voltmeter.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4&gt;Hardware Configuration&lt;/h4&gt;

&lt;p&gt;For being able to measure the luminous flux, we need to measure the resistance of the VT93N1 photo resistor, then use a formula to map this to the corresponding LUX value. In &lt;a href=&quot;#fig17&quot;&gt;Figure 17&lt;/a&gt; is shown how to connect the VT93N1 photo resistor to an Arduino UNO board, and for more details, in &lt;a href=&quot;#fig18&quot;&gt;Figure 18&lt;/a&gt; the circuit diagram is also shown.&lt;/p&gt;

&lt;figure id=&quot;fig17&quot;&gt;&lt;img alt=&quot;VT93N1 Sensor Connected to an Arduino UNO Board.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-VT93N1-breadboard.png&quot; /&gt;
&lt;figcaption&gt;Figure 17: VT93N1 Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig18&quot;&gt;&lt;img alt=&quot;Circuit Diagram of a VT93N1 Sensor Connected to an Arduino UNO Board.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Fritzing-VT93N1-schematics.png&quot; /&gt;
&lt;figcaption&gt;Figure 18: Circuit Diagram of a VT93N1 Sensor Connected to an Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Due to the relatively low accuracy of the VT93N1 sensor and also because of the high variations of light in a real environment, it is possible to obtain relatively high fluctuations, even if looks to be no change in the light, as perceived by the human eyes. This is relative, and for being able to characterize the performance of your sensor, a higher accuracy LUX-meter device may be required.&lt;/p&gt;

&lt;p&gt;Without an initial calibration, using a high precision LUX-meter, the error factor may be as high as 20%. This can be reduced to about 5-10%, when using high precision resistors with a well known value, a good voltmeter for initial voltage drop measurements and a high precision LUX-meter. However, this is only needed if you&#039;ll need to use this sensor for sensitive projects. To detect if is getting dark in a room, so a light turns on automatically, or to check if some plants have enough light in their current location (plants can tolerate high light variations) this cheap sensor even without any initial calibration is sufficient.&lt;/p&gt;

&lt;h4&gt;Software Configuration&lt;/h4&gt;

&lt;p&gt;We deal with an analog devices, that point us in using an analog pin of our Arduino UNO board, e.g., pin A1 for this example.&lt;/p&gt;

&lt;pre&gt;
#define VT93N1_PIN A1
&lt;/pre&gt;

&lt;p&gt;As in all our examples, we use the Arduino serial monitor to show sensor data. In addition, the sensor datasheet tells us that at least 5 seconds are needed for having the sensor adapted to the environmental light, so a 5 seconds delay is used at startup.&lt;/p&gt;

&lt;pre&gt;
void setup() {
  Serial.begin(115200);
  delay(5000);
}
&lt;/pre&gt;

&lt;p&gt;Since the datasheet does not provide a mapping function to transform a resistance value into a LUX value, we&#039;ll need to use our friend Google, which soon provide us with an response. The formula we can use is: &lt;code&gt;E = 341.64 / R^(10 / 9)&lt;/code&gt;, where E is the luminous emittance in LUX, and R is the resistance in kΩ (kilo ohms).&lt;/p&gt;

&lt;pre&gt;
void loop() {
  double vAcrossR2 = 0, r1 = 0, luxValue = 0,
         vInput = 5, r2 = 10000;
  
  // collect 10 samples and average to obtain stable value.
  for ( byte i = 0; i &amp;lt; 10; i++) {
    // read voltage from pin, in Volts
    vAcrossR2 += analogRead(VT93N1_PIN) * 0.00488;
  }
  vAcrossR2 = vAcrossR2 / 10.0;

  // calculate resistance r1 = 22 * (vInput / vAcrossR1 - 1)
  r1 = r2 * ( vInput / vAcrossR2 - 1);

  // convert resistance value to LUX value for this sensor based in formula:
  // E = 341.64 / R^(10 / 9), where R is measured in kOhm
  luxValue = 341.64 / pow( r1 / 1000.0, 10.0 / 9.0);

  Serial.print(&quot;LUX: &quot;);
  Serial.println(luxValue);

  delay(5000);
}&lt;/pre&gt;

&lt;p&gt;There are a few points in the code that requires explanations:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;Computing the resistance is made as shown below in this tutorial, with respect to a voltage divider circuit, using the equation: &lt;code&gt;R1 = R2 * (V_input / V_across_R2 - 1)&lt;/code&gt;.&lt;/li&gt;
	&lt;li&gt;Ten samples of ADC readings are taken, to improve the stability.&lt;/li&gt;
	&lt;li&gt;The &lt;code&gt;pow&lt;/code&gt; method is used to calculate the exponential value: its first argument is the base and the second is the exponent.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If all went fine, you should see the Serial Monitor window showing information similar with &lt;a href=&quot;#fig19&quot;&gt;Figure 19&lt;/a&gt;.&lt;/p&gt;

&lt;figure id=&quot;fig19&quot;&gt;&lt;img alt=&quot;Serial Monitor Showing VT93N1 Sensor Readings.&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/Serial-Monitor-VT93N1.png&quot; /&gt;
&lt;figcaption&gt;Figure 19: Serial Monitor Showing VT93N1 Sensor Readings.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2&gt;Some Points of Attention&lt;/h2&gt;

&lt;p&gt;The examples from this tutorial show how to use the sensors with an Arduino UNO board. However, the same code and connections work with almost any other Arduino board. It is important to notice that some Arduino boards, such as Arduino DUE, use 3.3V as input (VCC = 3.3V). Therefore, you should use sensors that are able to receive power from a 3.3V source instead of 5V one. This is required for being able to directly connect sensor pins to Arduino pins without destroying your Arduino board.&lt;/p&gt;

&lt;p&gt;There are cases when we really want or need to use a 3.3V an Adruino board with a 5V powered sensor, or a 5V Arduino board with a 3.3V sensor. The solution for this problem is to use &lt;code&gt;voltage level converter&lt;/code&gt;. It is possible to build one by using small FETs (Field Effect Transistors) or by using voltage divider circuit (not the most recommended way, but still the cheapest and easiest) or you can simply buy a specially designed board which takes care of such tasks. In &lt;a href=&quot;#fig20&quot;&gt;Figure 20&lt;/a&gt; is shown such a ready to use small board that provides four I/O level converter pins from 3/3.3V to 5V and back. Such boards costs as less as 1-2€ per piece, postage in EU included (e.g., use &lt;a href=&quot;http://www.ebay.com/sch/i.html?_nkw=Level+Conversion+Module+5V-3V&quot;&gt;eBay&lt;/a&gt;).&lt;/p&gt;

&lt;figure id=&quot;fig20&quot;&gt;&lt;img alt=&quot;Two ways, four channels, 3.3V to 5V Voltage Level Converter&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/sensors/HV-LV-Converter.png&quot; /&gt;
&lt;figcaption&gt;Figure 20: Two ways, four channels, 3.3V to 5V Voltage Level Converter.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Another special attention has to be paid to the power supplyused for your project. Cheap ones comes usually with low regulation, that is, the maximum ±5% allowed tolerance is not really what we get, thus causing all kind of strange problems with your micro-controller, such as resets. This is even worst when using analog sensors, which are usually highly sensitive to voltage variation, and even a ±1% variation may reduce the accuracy to a few levels of magnitude. As a general advice, either use a high quality power source (that can be expensive for a DIY project!), or at least add a 0.1µF ceramic capacitor in parallel with a 100µF (or larger, up to 1000µF) electrolytic capacitor on the power supply line, before any other device in the circuit. This allows for high frequency (the small ceramic capacitor) and low frequency (the larger electrolytic capacitor) spikes filtering (at some level), thus improving the general behavior of the circuit.&lt;/p&gt;

&lt;h2&gt;Next Tutorial: Part 3 - WiFI Network Connection and Cloud Data Storage&lt;/h2&gt;

&lt;p&gt;In this tutorial we&#039;ll learn how to use an ESP8266 WiFi module (there are 13 or more different variations) to connect an Arduino based sensor node to network, and use free online services to store data for later analyze, or provide charts showing the evolution of the measured environment properties over time.&lt;/p&gt;

&lt;p&gt;The ESP8266 WiFI module is a cheap way to empower a device very limited in resources, such as the Arduino UNO board, with a standard 802.11g/b/n WiFi network connection, and allow it to communicate (as a client) with another devices, or services, by using standard HTTP/HTTPS protocols, i.e., GET, POST and PUT methods. In addition, custom UDP based communication is also possible when using ESP8266 WiFi module and the right firmware.&lt;/p&gt;

&lt;p&gt;Stay tuned, the release date is: before 10 May 2016.&lt;/p&gt;
&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;section class=&quot;field field-name-field-category field-type-taxonomy-term-reference field-label-above view-mode-rss&quot;&gt;&lt;h2 class=&quot;field-label&quot;&gt;Category:&amp;nbsp;&lt;/h2&gt;&lt;ul class=&quot;field-items&quot;&gt;&lt;li class=&quot;field-item even&quot;&gt;&lt;a href=&quot;/Arduino&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;Arduino&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item odd&quot;&gt;&lt;a href=&quot;/taxonomy/term/40&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;WoT&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item even&quot;&gt;&lt;a href=&quot;/taxonomy/term/43&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;C/C++&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item odd&quot;&gt;&lt;a href=&quot;/taxonomy/term/45&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;Sensor&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item even&quot;&gt;&lt;a href=&quot;/taxonomy/term/47&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;Digital&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item odd&quot;&gt;&lt;a href=&quot;/taxonomy/term/48&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;Analog&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/section&gt;&lt;div class=&quot;easy_social_box clearfix horizontal easy_social_lang_und&quot;&gt;
            &lt;div class=&quot;easy_social-widget easy_social-widget-twitter first&quot;&gt;&lt;a href=&quot;http://twitter.com/share&quot; class=&quot;twitter-share-button&quot;
data-url=&quot;https://web-engineering.info/node/61&quot;
data-count=&quot;horizontal&quot;
data-lang = &quot;en&quot;
data-via=&quot;&quot;
data-related=&quot;:Check it out!&quot;
data-text=&quot;WoT with Arduino for Beginners: Part 2 - Connecting to the Real World via Sensors&quot;&gt;Tweet&lt;/a&gt;&lt;/div&gt;
          &lt;div class=&quot;easy_social-widget easy_social-widget-facebook&quot;&gt;&lt;fb:like href=&quot;https://web-engineering.info/node/61&quot; send=&quot;true&quot; layout=&quot;button_count&quot; width=&quot;88&quot; show_faces=&quot;true&quot; action=&quot;like&quot; colorscheme=&quot;light&quot; font=&quot;&quot;&gt;&lt;/fb:like&gt;&lt;/div&gt;
          &lt;div class=&quot;easy_social-widget easy_social-widget-googleplus&quot;&gt;&lt;div class=&quot;g-plusone&quot; data-size=&quot;medium&quot; data-annotation=&quot;bubble&quot; data-href=&quot;https://web-engineering.info/node/61&quot;&gt;&lt;/div&gt;&lt;/div&gt;
          &lt;div class=&quot;easy_social-widget easy_social-widget-linkedin last&quot;&gt;&lt;script type=&quot;in/share&quot; data-url=&quot;https://web-engineering.info/node/61&quot; data-counter=&quot;right&quot;&gt;&lt;/script&gt;&lt;/div&gt;
  &lt;/div&gt; &lt;!-- /.easy_social_box --&gt;</description>
 <pubDate>Fri, 08 Apr 2016 09:41:02 +0000</pubDate>
 <dc:creator>mdiaconescu</dc:creator>
 <guid isPermaLink="false">61 at https://web-engineering.info</guid>
 <comments>https://web-engineering.info/node/61#comments</comments>
</item>
<item>
 <title>WoT with Arduino for Beginners: Part 1 - Mastering the RGB LED</title>
 <link>https://web-engineering.info/node/60</link>
 <description>&lt;div class=&quot;field field-name-body field-type-text-with-summary field-label-hidden view-mode-rss&quot;&gt;&lt;div class=&quot;field-items&quot;&gt;&lt;div class=&quot;field-item even&quot; property=&quot;content:encoded&quot;&gt;&lt;p&gt;In this multi-part tutorial we show how to develop Arduino-based apps for the Web of Things (WoT). This first part shows the very basics of an Arduino program (known as a &quot;sketch&quot;) and provides a quick introduction to some electronic components, such as resistors, RGB LEDs and LEDs in general. In the following parts of this tutorial, which will appear every 1-2 weeks, we discuss how to read sensors, control actuators, and how to connect them all together in a Web of Things (WoT) network. Using standard Web technologies, such as HTTP and Web Sockets, we can then access the data or provide commands to the WoT nodes. As a newbie, it is helpful if you already have some basic C/C++ programming knowledge and understanding of some Web standards and programming languages, such as HTML and JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;small&gt;&lt;strong&gt;Disclaimer:&lt;/strong&gt; working with electricity is dangerous. For this project we&#039;ll use 5V, which is safe for the human body under any environment conditions. However, the low voltage may be obtained from a mains connected power brick, and therefore we highly recommend you to take safety precautions and to use a trustful brand for the power supply. We cannot be held responsible for any caused damage! Do it at your own risk and/or ask help from an electronics engineer. In case you are using the USB connector from your PC to power the Arduino board, be aware that short-circuits which may occur on the Arduino board may also have a negative impact on your PC!&lt;/small&gt;&lt;/p&gt;

&lt;p style=&quot;margin-top:1em&quot;&gt;&lt;small&gt;&lt;strong&gt;Credits:&lt;/strong&gt; some of the images from this tutorial are created by using &lt;a href=&quot;http://fritzing.org/home/&quot;&gt;Fritzing&lt;/a&gt;, a nice electronics modeling tool for beginners.&lt;/small&gt;&lt;/p&gt;

&lt;h4&gt;&lt;strong&gt;&lt;a href=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/WoT-Tutorial-Part1.zip&quot;&gt;Download Source Code&lt;/a&gt;&lt;/strong&gt;&lt;/h4&gt;

&lt;h2&gt;The Arduino Story&lt;/h2&gt;

&lt;p&gt;The name &lt;em&gt;Arduino&lt;/em&gt; comes from a bar in Ivrea, Italy, where some of the founders of the project used to meet. Today, this term is well known as referring to a project and a community.&lt;/p&gt;

&lt;p&gt;All started when Hernando Barragán, a Colombian student, created the development platform &lt;a href=&quot;https://en.wikipedia.org/wiki/Wiring_(development_platform)&quot;&gt;Wiring&lt;/a&gt; as his Master thesis project in 2004. The goal was to create low-cost, simple tools for non-engineers to create digital projects. The Wiring platform consisted of a hardware PCB with an ATmega128 micro-controller, an integrated development environment (IDE) based on &lt;a href=&quot;https://en.wikipedia.org/wiki/Processing_(programming_language)&quot;&gt;Processing&lt;/a&gt;, and library functions to easily program the micro-controller. In 2005, Massimo Banzi, with David Mellis (then an IDII student) and David Cuartielles, added support for the cheaper ATmega8 micro-controller to Wiring. The two forked the Wiring source code and started running it as a separate project, called &lt;em&gt;Arduino&lt;/em&gt;. The Arduino&#039;s initial core team consisted of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David Mellis.&lt;/p&gt;

&lt;p&gt;The project is based on micro-controller board designs, produced by several vendors, using various micro-controllers. These systems provide sets of digital and analog I/O pins that can interface to various expansion boards (also called &#039;shields&#039;) and other circuits. The boards feature serial communication interfaces, including Universal Serial Bus (USB) on some models, for loading programs from personal computers. For programming the micro-controllers, the Arduino project provides an integrated development environment (IDE) based on a programming language named &lt;em&gt;Processing&lt;/em&gt;, which also supports the languages C and C++.&lt;/p&gt;

&lt;p&gt;The first Arduino was introduced in 2005, aiming to provide a low cost, easy way for novices and professionals to create devices that interact with their environment using sensors and actuators. Common examples of such devices intended for beginner hobbyists include simple robots, thermostats, and motion detectors.&lt;/p&gt;

&lt;p&gt;Today, there is a large number of various types of Arduino boards. They are different in hardware capabilities (MCU type, RAM size, number of I/O pins, size, etc), but they all share a common IDE and programming language.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;https://www.arduino.cc/en/Main/Software&quot;&gt;Arduino IDE&lt;/a&gt; is not the only way, and not necessarily the best way to program an Arduino development board. However, it is by far the easiest way to start with Arduino, and enter the world of &lt;em&gt;Do it Yourself&lt;/em&gt; control. It supports the whole multitude of Arduino boards, and internally takes care of all the software and hardware variations, leaving as the only important task the writing of an &quot;almost&quot; hardware-independent program.&lt;/p&gt;

&lt;h2&gt;Contents of this Tutorial&lt;/h2&gt;

&lt;p&gt;The following main topics are discussed:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;How to write the first Arduino program.&lt;/li&gt;
	&lt;li&gt;What are (RGB) LEDs and how to use them.&lt;/li&gt;
	&lt;li&gt;Using the RGB LED as single color indicator.&lt;/li&gt;
	&lt;li&gt;Use PWM (pulse width modulation) to emulate analog voltages and create &quot;real&quot; colors with the RGB LED.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;For this project we need the following software and hardware components:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;The &lt;a href=&quot;https://www.arduino.cc/en/Main/Software&quot;&gt; official Arduino IDE&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;An &lt;a href=&quot;https://www.arduino.cc/en/Main/ArduinoBoardUno&quot;&gt;Arduino/Genuino UNO R3&lt;/a&gt; or &lt;a href=&quot;https://www.arduino.cc/en/Main/ArduinoBoardNano&quot;&gt;Arduino Nano 3.x&lt;/a&gt; board. Other Arduino boards (MEGA2560, Micro, Mini, etc) work as well, but some of the instructions may be slightly different.&lt;/li&gt;
	&lt;li&gt;An RGB LED. For this tutorial we&#039;ll use a common cathode one (common GND pin for all three LEDs).&lt;/li&gt;
	&lt;li&gt;Three resistors: 2 x 330Ω and 1 x 220Ω.&lt;/li&gt;
	&lt;li&gt;A breadboard and a few jumper wires.&lt;/li&gt;
	&lt;li&gt;A power supply for your arduino board (7 - 12V is recommended, 5.5/2.1 center positive connector). A simpler alternative for this project is to use an USB Type B Male connector (for Arduino UNO) or USB Mini A Male (for Arduino Nano), and power if from an USB port of your PC. That&#039;s required anyway, in order to upload the program to the Arduino board.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;a href=&quot;https://www.arduino.cc/en/Main/ArduinoBoardUno&quot;&gt;Arduino UNO R3&lt;/a&gt; board (see &lt;a href=&quot;#fig1&quot;&gt;Figure 1&lt;/a&gt;) is equipped with the ATmega 328p MCU, running at 16MHz. It comes with 2KB of RAM memory, 32KB of flash memory (used for the program) and 1KB of EEPROM memory. Only 31.5KB of the flash memory is available, 0.5KB are used by the Arduino bootloader (a piece of software running on the MCU which allows you to easily upload the program to the board without the complications of a special programmer device). The board provides 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a power jack, an ICSP header (used to program the MCU with an external programmer) and a reset button. A maximum of 40mA (no more than 200mA in total) is provided by the board.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;https://www.arduino.cc/en/Main/ArduinoBoardNano&quot;&gt;Arduino Nano 3.x&lt;/a&gt; board (see &lt;a href=&quot;#fig1&quot;&gt;Figure 1&lt;/a&gt;) is equipped with the ATmega 328 (or ATmega 328p for some clones) MCU, running at 16MHz. It comes with 2KB of RAM memory and 32KB of flash memory, and 1KB of EEPROM memory. Only 30KB of the flash memory are usable, 2KB are used by the Arduino bootloader. The board provides 14 digital input/output pins (of which 6 can be used as PWM outputs), 8 analog inputs and a reset button.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Notice that some older versions of Arduino Nano (under version 3) comes with an ATmega 168 (or 168p for some clones), thus the amount of RAM, flash and EEPROM are half of the values available in the Arduino Nano 3.x.&lt;/p&gt;

&lt;figure id=&quot;fig1&quot;&gt;&lt;img alt=&quot;Arduino UNO R3 and Nano 3&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/arduino-boards.png&quot; /&gt;
&lt;figcaption&gt;Figure 1: Arduino UNO R3 and Nano 3&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2&gt;What is a (RGB) LED?&lt;/h2&gt;

&lt;p&gt;An LED (Light Emitting Diode) is a diode that emits lights when connected to a correct power source. LEDs comes in different shapes or colors, but basically they follow the same concept. &lt;a href=&quot;#fig2&quot;&gt;Figure 2&lt;/a&gt; shows various LEDs and the LED symbol used in electronic schematics. The cathode represents the negative pin, and in many cases this identifies with the circuit GND (ground). However, the negative and the GND of a circuit must not be confused, because they may or may not represent the same thing on a specific circuit. The anode is the positive pin, usually named VCC or simply +.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node:&lt;/strong&gt; in real physics, the electrons are traveling (thus creating the current) from the negative pol to the positive pol. However, in electronic diagrams, the symbols are used other way around, because earlier, when these symbols were created, there was no real way to know how the electrons are moving, therefore the scientist at that time believed that the electrons moves from the positive pol to the negative one.&lt;/p&gt;

&lt;figure id=&quot;fig2&quot;&gt;&lt;img alt=&quot;RGB LED&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/led-example.png&quot; /&gt;
&lt;figcaption&gt;Figure 2: Various LEDs and the Electronic Schematics Symbol&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;An RGB LED (see &lt;a href=&quot;#fig3&quot;&gt;Figure 3&lt;/a&gt;) consists of three individual (one red, one green and one blue) LEDs in a single unit. These LEDs come either with a common cathode (negative pin) or with a common anode (positive pin). This is important to know in order to wire it correctly to a circuit.&lt;/p&gt;

&lt;figure id=&quot;fig3&quot;&gt;&lt;img alt=&quot;RGB LED&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/rgb-led.png&quot; /&gt;
&lt;figcaption&gt;
&lt;ul&gt;
	&lt;li&gt;Figure 3: Common Cathode and Common Anode RGB LED&lt;/li&gt;
&lt;/ul&gt;
&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;A LED is a current controlled device, which means that it is important to determine the amount of current flowing through the LED. A LED has a maximum current specified by its datasheet, and when this information is not available, for standard 3mm or 5mm LEDs, but not only, one can safely assume 20mA (0.02A) as the maximum value. Knowing the voltage applied to the LED pins (e.g., 3.3V, 5V, 12V, etc), and the LED forward voltage, we can use the Ohm&#039;s law, &lt;code&gt;V = I * R&lt;/code&gt;, to determine the value of a resistor which ensures that the maximum current is not exceeded. Thus, &lt;code&gt;R = V / I&lt;/code&gt;, where R is the resistence value in Ohms, V is the voltage in volts and I is the current in amperes.&lt;/p&gt;

&lt;p&gt;A resistor is a passive electronic component which restrict the amount of current passing through it. By analogy, a water tab is used to control the amount of water flow, so is the resistor, but instead of water, it controls the amount of electrons (thus the current) allowed to flow throug it.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;LED forward voltage&lt;/em&gt; is the the voltage level at which the led to starts to emit light (because it allows just enough current to pass trough). Common LED forward voltage values are: 1.7V for red, 2V for green and orange and 2.7V for white and blue.&lt;/p&gt;

&lt;p&gt;For a value of 5V applied to the LED circuitry (which is the case with our Arduino UNO example), we can compute the resistor value for an red LED:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;Determine the voltage to be dropped outside the LED. This is the difference between the voltage applied to the circuit and the LED forward voltage. For the red LED this is: 5V - 1.7V = 3.3V.&lt;/li&gt;
	&lt;li&gt;Decide how much current you want to allow passing through the LED. The amount of current determines the LED brightness. In general, half of the maximum specified current is just sufficient, which for a normal 3mm or 5mm LED is about 10mA (0.01A).&lt;/li&gt;
	&lt;li&gt;Apply the Ohm&#039;s law: &lt;code&gt;R = 3.3 / 0.01&lt;/code&gt;, resulting in &lt;code&gt;R = 330Ω.&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Like with any LED, resistors are are required for the RGB LEDs, thus limiting the current and protecting the LED. For an RGB LED we need three resistors, one for each color. Following the above rule, we have:&lt;/p&gt;

&lt;ul&gt;
	&lt;li&gt;Voltage to be &lt;em&gt;dropped&lt;/em&gt; outside the LED: &lt;code&gt;5V - 1.7V = 3.3V&lt;/code&gt; for the red LED, &lt;code&gt;5V - 2V = 3V&lt;/code&gt; for the green LED, and &lt;code&gt;5V - 2.7V = 2.3V&lt;/code&gt; for the blue LED. Therefore, the voltage to be dropped out is: &lt;code&gt;V = {3.3V (red), 3V (green), 2.3V (blue)}&lt;/code&gt;.&lt;/li&gt;
	&lt;li&gt;Knowing that we need 10mA (0.01A) current applied to the LED, we compute the resistor values by using the Ohm&#039;s law, &lt;code&gt;R = V / I&lt;/code&gt;. We obtain: &lt;code&gt;R = { 3.3 / 0.01 (red), 3.0 / 0.01 (green), 2.3 / 0.01 (blue)}, &lt;/code&gt; &lt;code&gt;R = {330Ω (red), 300Ω (green), 230Ω (blue)}&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Resistors can be found in various values, but unfortunately not all the resistor values we obtained above are standard ones. However, we can approximate these values with the first lower or upper (whichever is convenient for us) standard values, so we obtain, &lt;code&gt;R = {330Ω (red), 330Ω (green), 220Ω (blue)}&lt;/code&gt;. This means that the real current passing through our LEDs is &lt;code&gt;I = {10mA (red), 9mA (green), 10.4mA (blue)}&lt;/code&gt;. It is possible to use resistors in series or parallel (or both), to obtain more exact values, or we can buy expensive resistors which have the exact value we need, but there is no reason to do this if the purpose is just to have the LED lighting up.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; we use a common cathode RGB LED, so the resistors are connected to the LED&#039;s anodes. Using a common anode RGB led requires to connect the resistor to LED&#039;s anodes, and also to make a few changes in the Arduino program.&lt;/p&gt;

&lt;h2&gt;The Basics of an Arduino Program (Sketch)&lt;/h2&gt;

&lt;p&gt;An Arduino program or sketch is essentially a C/C++ program. It comes with a set of methods (implemented in the core) which allows to control the Arduino I/O pins, communicate over UART, I2C, SPI or read analog values from a voltage source. Every Arduino code consists of the following (some optional) sections:&lt;/p&gt;

&lt;pre&gt;
// 1) constants definition (optional if no constant is needed)
// 2) include headers for used libraries ( optional if no library is used)
// 3) define the global variables (optional if no global variable is required)

// program initialization
&lt;strong&gt;void setup()&lt;/strong&gt; { 
  // I will run just once, when board is powered on, or a reset signal is received.
  // I will also execute if you explicitly call me in the program, but please don&#039;t do that!
}

// infinite loop cycle
&lt;strong&gt;void loop()&lt;/strong&gt; { 
  // I will run again and again, in a loop, as long as the board is powered.
}&lt;/pre&gt;

&lt;p&gt;While the sections marked 1), 2) and 3) are optional, in most of the Arduino programs you&#039;ll use at least one if not all of them.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;setup&lt;/code&gt; method executes only once, when the Arduino board is powered up or when a reset signal is received. This method contains initialization code, such as set pin modes (we discuss later about this), initializing serial communication and so on. The &lt;code&gt;loop&lt;/code&gt; method, as also suggested by its name, executes in an infinite loop. This method contains the code that your MCU (micro-controller) executes again and again, such as reading a sensor, or counting the elapsed time.&lt;/p&gt;

&lt;h2&gt;Compile and Upload an Arduino Program&lt;/h2&gt;

&lt;p&gt;While the above program does nothing, we use it to show how to compile and upload a program to an Arduino board. We mostly refer to Arduino UNO board, but the procedure for the other Arduino boards is very similar (one just need to chose the correct board from the IDE menu).&lt;/p&gt;

&lt;p&gt;Open the Arduino IDE, then navigate to &lt;code&gt;File &amp;gt; New&lt;/code&gt; top bar main menu. Copy/paste the above code example, then navigate to &lt;code&gt;File &amp;gt; Save&lt;/code&gt;. Give a name (e.g., &lt;code&gt;rgb_led&lt;/code&gt;) to your program and then save it. You should have now a result as shown in &lt;a href=&quot;#fig4&quot;&gt;Figure 4&lt;/a&gt;.&lt;/p&gt;

&lt;figure id=&quot;fig4&quot;&gt;&lt;img alt=&quot;Arduino Dummy Program&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/arduino-ide-dummy.png&quot; /&gt;
&lt;figcaption&gt;Figure 4: The Most Useless Arduino UNO Program Ever.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;Navigage to &lt;em&gt;Tools &amp;gt; Board&lt;/em&gt; and select &lt;em&gt;Arduino/Genuino UNO&lt;/em&gt;. Last, navigate to &lt;em&gt;Tools &amp;gt; Port&lt;/em&gt; and select the COM port associated with your Arduino Uno Board (usually is the only COM port in the list, or is the one that is not COM1). If all went fine, then expanding the &lt;em&gt;Tools&lt;/em&gt; menu you should see something similar with &lt;a href=&quot;#fig5&quot;&gt;Figure 5&lt;/a&gt; (the COM port may be different, the rest must be the same).&lt;/p&gt;

&lt;figure id=&quot;fig5&quot;&gt;&lt;img alt=&quot;Arduino IDE Configuration&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/arduino-ide-board.png&quot; /&gt;
&lt;figcaption&gt;Figure 5: Arduino IDE Configured for Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;When using Arduino Nano 3.x, make sure to select the &lt;em&gt;Arduino Nano&lt;/em&gt; from the &lt;em&gt;Tools &amp;gt; Board&lt;/em&gt; menu. An additional menu is shown, &lt;em&gt;Tools &amp;gt; Processor&lt;/em&gt; allowing to select 328 or 168 MCU. Selecting 328 works also on the clone boards using 328p MCU, and the same, selecting 168 MCU works also with some clone boards using the 168p MCU.&lt;/p&gt;

&lt;p&gt;Last, we compile and upload the program to the Arduino UNO board (the procedure for Arduino Nano is exactly the same). This is achieved with a simple click of a button: the arrow button located in the top-left corner (as marked with a red circle in &lt;a href=&quot;#fig6&quot;&gt;Figure 6&lt;/a&gt;). Alternatively, use the &lt;em&gt;Sketch &amp;gt; Upload&lt;/em&gt; menu. If all went fine, you should see the &quot;Done Uploading&quot; text in the green bar, just under the sketch edit area (see the rectangle red mark in &lt;a href=&quot;#fig6&quot;&gt;Figure 6&lt;/a&gt;).&lt;/p&gt;

&lt;figure id=&quot;fig6&quot;&gt;&lt;img alt=&quot;Arduino IDE Upload Program&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/arduino-ide-upload.png&quot; /&gt;
&lt;figcaption&gt;Figure 6: Compile and Upload Sketch with the Arduino IDE.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;It is important to notice the information shown in the info area (black area at the bottom of the application interface). It states amount of flash memory used by this program (450 Bytes) and the amount of RAM used by the global variables (9 Bytes). You may wonder, why so much flash and RAM is taken for a program which does nothing? Well, this happens because there is some additional code, part of the Arduino core code that is compiled and added to the program, behind the scene.&lt;/p&gt;

&lt;h2&gt;Master the RGB LED: the Hardware Configuration&lt;/h2&gt;

&lt;p&gt;In &lt;a href=&quot;#fig7&quot;&gt;Figure 7&lt;/a&gt; is shown how to wire the RGB LED to the Arduino UNO board, by using the three resistors and a set of jumper wires. If you don&#039;t have a breadboard and also no jumper wires, you can use the resistor leads as wires, and connect them directly to Arduino UNO board header pin. While that&#039;s a kind of hack, it is easy to perform, and requires no additional components than the Arduino board, the RGB LED and the resistors. &lt;a href=&quot;fig8&quot;&gt;Figure 8&lt;/a&gt; shows the schematics of the circuit.&lt;/p&gt;

&lt;figure id=&quot;fig7&quot;&gt;&lt;img alt=&quot;Arduino UNO Breadboard&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/breadboard_uno.png&quot; /&gt;
&lt;figcaption&gt;Figure 7: Breadboard Wiring of the RGB LED to the Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;#fig8&quot;&gt;&lt;img alt=&quot;Arduino UNO Schematics&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/schematics_uno.png&quot; /&gt;
&lt;figcaption&gt;Figure 8: Schematics Wiring of the RGB LED to the Arduino UNO Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;In &lt;a href=&quot;#fig9&quot;&gt; Figure 9&lt;/a&gt; is shown the breadboard arrangement for the RGB LED when the Arduino Nano 3.x board is used.&lt;/p&gt;

&lt;figure id=&quot;fig9&quot;&gt;&lt;img alt=&quot;Arduino Nano Breadboard&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/breadboard_nano.png&quot; /&gt;
&lt;figcaption&gt;Figure 9: Breadboard Wiring of the RGB LED to the Arduino Nano Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;figure id=&quot;fig10&quot;&gt;&lt;img alt=&quot;Arduino Nano Schematics&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/schematics_nano.png&quot; /&gt;
&lt;figcaption&gt;Figure 10: Schematics Wiring of the RGB LED to the Arduino Nano Board.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2&gt;Master the RGB LED: the Software Configuration&lt;/h2&gt;

&lt;p&gt;In this section we show how to write an Arduino program, allowing to light up the RGB LED in various color combinations. Notice that the code is common for both, the Arduino UNO R3 and Arduino Nano 3.x boards, therefore when we say &quot;Arduino broard&quot; we refer to either of the two Arduino boards. In addition, the exact same sketch code will work in most of the Arduino boards.&lt;/p&gt;

&lt;h3&gt;Arduino I/O Capabilities&lt;/h3&gt;

&lt;p&gt;Controlling the RGB LED means to be able to individually light up each of the three component LEDs. That is, using some of the Arduino pins, we should be able to allow (or stop) the current to flow through the LED. Each Arduino board has a number of pins named general purpose I/O (input/output) pins. In addition, some of the pins are capable of analog input (ADC) or analog output (DAC or PWM). Finally, some of the pins have special features, as being able to communicate by using some standard protocols, such as &lt;a href=&quot;https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter&quot;&gt;U(S)ART&lt;/a&gt; (Universal (Synchronous) Asynchronous Receiver/Transmitter), &lt;a href=&quot;https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus&quot;&gt;SPI&lt;/a&gt; (Serial Peripheral Interface) or &lt;a href=&quot;https://en.wikipedia.org/wiki/I%C2%B2C&quot;&gt;I2C&lt;/a&gt; (I square C).&lt;/p&gt;

&lt;h4&gt;Digital Output&lt;/h4&gt;

&lt;p&gt;A &lt;em&gt;digital output pin&lt;/em&gt; is a pin that is able to change its state into HIGH (that is usually very close to the VCC value) or LOW (that is GND), whenever the running program tells it to do so. That means, we can write code, that allows to transform that pin into either a VCC or GND connection. In simple words, inside the MCU there are transistors (some miniaturized as electronic switches), able to bound the pin either to VCC or to GND.&lt;/p&gt;

&lt;p&gt;It is important to notice, that while your power supply used for the Arduino board may be able to deliver a lot of current, (maybe 500mA via an USB 2.0 port or more tha 1A from a power brick supply), each of the Arduino pins are only able to support up to 40mA. So we can use an Arduino pin to light up a LED (we saw that this means about 10mA per LED) or transmit a signal, but it is NOT possible to power up a motor or an electromagnet in this manner. Ignore this rule and you&#039;ll either have a dead pin or a even a dead Arduino board. Also, the total current (for all the pins used at a moment in time) must not exceed 200mA. Notice that these values are already maximum values, and should not be used for long time. Use values under 80% of these maximums to be in a safe margin and protect your board.&lt;/p&gt;

&lt;p&gt;In this section we&#039;ve used a few new terms:&lt;/p&gt;

&lt;dl&gt;
	&lt;dt&gt;Digital&lt;/dt&gt;
	&lt;dd&gt;it refers to a signal which can be either LOW (equivalent of binary 0) or HIGH (equivalent of binary 1). A sequence of such states can be interpreted as a set of binary data, used to communicate with a digital device, using a communication protocol.&lt;/dd&gt;
	&lt;dt&gt;HIGH&lt;/dt&gt;
	&lt;dd&gt;is a digital state, where the voltage level is close to VCC.&lt;/dd&gt;
	&lt;dt&gt;LOW&lt;/dt&gt;
	&lt;dd&gt;is a state, where the voltage level is close to GND.&lt;/dd&gt;
&lt;/dl&gt;

&lt;p&gt;Please note that while in many cases &lt;code&gt;HIGH&lt;/code&gt; refers to a voltage almost equal with VCC, and LOW is a voltage level close to GND, this may be different form case to case. For example, in some systems, HIGH may be equal with VCC, but may also mean any voltage level in the inverval [VCC / 2, VCC]. In the same way, LOW may mean GND, but also any voltage level in the interval [GND, VCC / 2).&lt;/p&gt;

&lt;h4&gt;Digital Input&lt;/h4&gt;

&lt;p&gt;A &lt;em&gt;digital input pin&lt;/em&gt; is a pin that is able to detect changes of HIGH or LOW coming from some external source. In other words, with an digital input pin we are able to &quot;read&quot; HIGH or LOW digital events, coming for example from sensors or other voltage sources. With a digital input pin we can&#039;t light up LEDs or power up devices.&lt;/p&gt;

&lt;h4&gt;Analog Output&lt;/h4&gt;

&lt;p&gt;An &lt;em&gt;analog output pin&lt;/em&gt; is a pin which is able not only to transform to VCC or GND but also to voltage values in between. Such pins are not available for every Arduino boards, and they are named DAC pins (Digital to Analog Converter). For example, hardware DAC pins are available in the &lt;a href=&quot;https://www.arduino.cc/en/Main/ArduinoBoardDue&quot;&gt;Arduino DUE board&lt;/a&gt;. A solution to emulate DAC with an Arduino board which does not have such built in capabilities, is to use a technique named PWM (Pulse Width Modulation). We discuss this topic later in this tutorial. Both, Arduino UNO and Nano boards have six pins capable of PWM output.&lt;/p&gt;

&lt;h4&gt;Analog Input&lt;/h4&gt;

&lt;p&gt;An &lt;em&gt;analog input pin&lt;/em&gt; is a pin capable to detect voltage values within a range, which is usually [GND, VCC]. This is possible by using an internal ADC (Analog to Digital Converter) module, which is able to map the voltage level value in a number, representing the voltage quantity. This feature is very important and it is found in almost any Arduino board. Examples of using this feature are: analog sensors (provides a voltage level to tell you what is the measured quantity), voltmeters or ammeters.&lt;/p&gt;

&lt;h3&gt;Control the Individual Colors of the RGB LED&lt;/h3&gt;

&lt;p&gt;Using Arduino, we can light up individual LEDs by using Arduino digital output pins. Arduino digital pins are identified by using specific positive integer numbers, also printed out on the Arduino PCB board.&lt;/p&gt;

&lt;p&gt;Setting an Arduino pin as &lt;em&gt;Digital Output&lt;/em&gt; is possible by using the &lt;code&gt;pinMode&lt;/code&gt; method. It takes two arguments: 1) the pin number; and 2) a constant specifying the mode type: &lt;code&gt;INPUT&lt;/code&gt;, &lt;code&gt;OUTPUT&lt;/code&gt; or &lt;code&gt;INPUT_PULLUP&lt;/code&gt;. For our case, we need to use &lt;code&gt;OUTPUT&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We have used pin 9 to control the blue LED, pin 10 for the green LED and pin 11 for the red LED, as shown in &lt;a href=&quot;#fig7&quot;&gt;Figure 7&lt;/a&gt; and &lt;a href=&quot;#fig9&quot;&gt;Figure 9&lt;/a&gt;. Therefore, in the &lt;code&gt;setup&lt;/code&gt; method, we set these pins as digital output:&lt;/p&gt;

&lt;pre&gt;
void setup() {
  &lt;strong&gt;pinMode&lt;/strong&gt;(9, &lt;strong&gt;OUTPUT&lt;/strong&gt;);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}
&lt;/pre&gt;

&lt;p&gt;We like to implement the following LED effect: every of the three LEDs lights in the sequence red, green then blue, and each time the LED stays ON for about one second. To do that, we need to use some kind of &quot;pause&quot; in the Arduino code. This is possible using the &lt;code&gt;delay&lt;/code&gt; method, which has one parameter, the number of milliseconds for the &quot;pause&quot;. In addition, there is another method, named &lt;code&gt;delayMicroseconds&lt;/code&gt; allowing for smaller pause delays, in the range of microseconds.&lt;/p&gt;

&lt;p&gt;As we discussed, the &lt;code&gt;loop&lt;/code&gt; method executes again, and again. This is the place where our main code goes, and where we also like to use the &quot;pause&quot;.&lt;/p&gt;

&lt;pre&gt;
void loop() {
  delay(1000);
}
&lt;/pre&gt;

&lt;p&gt;To light up a LED, we&#039;ll need to enable (set HIGH) or disable (set LOW) the corresponding Arduino pins. This is possible by using the &lt;code&gt;digitalWrite&lt;/code&gt; method, which has two arguments: 1) the pin number; and 2) the state (HIGH or LOW).&lt;/p&gt;

&lt;pre&gt;
void loop() {
  digitalWrite(9, HIGH);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  delay(1000);
}&lt;/pre&gt;

&lt;p&gt;Now all the LEDs are light up but they stay ON all the time. We can go one step further and using a counter, we can determine when is the time to turn the LED ON or OFF.&lt;/p&gt;

&lt;pre&gt;
uint8_t step = 0;
void loop() {
  switch (step % 3) {
    case 0:
      &lt;strong&gt;digitalWrite&lt;/strong&gt;(9, &lt;strong&gt;HIGH&lt;/strong&gt;);
      &lt;strong&gt;digitalWrite&lt;/strong&gt;(10, &lt;strong&gt;LOW&lt;/strong&gt;);
      digitalWrite(11, LOW);
      break;
    case 1:
      digitalWrite(9, LOW);
      digitalWrite(10, HIGH);
      digitalWrite(11, LOW);
      break;
    case 2:
      digitalWrite(9, LOW);
      digitalWrite(10, LOW);
      digitalWrite(11, HIGH);
      break;
  }
  delay(1000);
  step++;
}&lt;/pre&gt;

&lt;p&gt;The result of the modulo operation &lt;code&gt;step % 3 &lt;/code&gt; is 0, 1 or 2. Thus for each of this value, we can assign a LED to be ON and all the other to be OFF.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Homework:&lt;/strong&gt; modify the code so that the red LED is on for one second, the green LED for two seconds and the blue LED for three seconds.&lt;/p&gt;

&lt;p&gt;Now compile and upload the code to your Arduino board and enjoy the light show! If you are ready for more, then read further.&lt;/p&gt;

&lt;h3&gt;Use PWM to create &quot;Real&quot; Colors with an RGB LED&lt;/h3&gt;

&lt;p&gt;We have a new idea: lets use the three LEDs and create mixture of colors, as done by our monitors or TVs (which in a way, use the same strategy to create the colorful images we see). But wait, wouldn&#039;t this mean to create the monitor with the smallest resolution in the world: 1 pixel! That sounds cool, right?&lt;/p&gt;

&lt;p&gt;Creating &quot;real&quot; colors, requires to find a way to obtain different levels of red, green and blue from our RGB LED. That will be possible if we are able to provide more (or less) current to the LED, thus obtaining various levels of brightness. From the hardware point of view, this means to either variate the resistor value or the voltage, thus controlling the current, which in turn determines the LED brightnes. But how do we do this via the Arduino code, since we don&#039;t want to use dozens or hundreds resistors, and we only have the 5V supply from our USB 2.0 port? Here is handy to have a DAC module, which will be able to transform a number into a voltage level. Unfortunately, we don&#039;t have one and the Arduino UNO and Nano boards come with no such built in module.&lt;/p&gt;

&lt;h4&gt;What is PWM Signal?&lt;/h4&gt;

&lt;p&gt;PWM describes a way to switch the voltage ON and OFF, for specific amounts of time, thus making the device connected to PWM output (e.g., the LED) to &quot;think&quot; that it actually gets less voltage.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;#fig11&quot;&gt;Figure 11&lt;/a&gt; shows how PWM works, with a square signal. A pair of LOW and HIGH signal is named &lt;em&gt;period&lt;/em&gt;. The number of period repetitions in the interval of one second is named &lt;em&gt;frequency&lt;/em&gt;. The amount of time from a period (measured in percent), for which the signal is HIGH represents the &lt;em&gt;duty cycle&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The important aspects are the frequency and the duty cycle. The frequency is somehow dependent on the device we try to &quot;lie&quot; about the voltage value. Using too low frequency values, may not trick the device in believing that it gets a lower voltage, or it may not work at all. The duty cycle determines the voltage quantity that is saw by the device (e.g., the LED). Normally, the duty cycle percent value from the real applied voltage, is what the device &quot;sees&quot;. E.g., duty cycle = 50%, real applied voltage = 5V, then the voltage observed by the device powered device is &lt;code&gt;50% * 5V = 2.5V&lt;/code&gt;.&lt;/p&gt;

&lt;figure id=&quot;fig11&quot;&gt;&lt;img alt=&quot;PWM Signal Example&quot; src=&quot;http://web-engineering.info/sites/default/files/wot_tutorials/rgb_led/pwm_example.png&quot; /&gt;
&lt;figcaption&gt;Figure 11: Example of PWM Signals.&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4&gt;Arduino and PWM&lt;/h4&gt;

&lt;p&gt;Most of the Arduino boards comes with built in PWM capabilities. The PWM capable pins are marked with ~ (tilde). Now it is obvious that we didn&#039;t chose the pins at random. All the pins we use, 9, 10, an 11 are PWM pins. Depending on the used Arduino board, more or less such pins are available.&lt;/p&gt;

&lt;p&gt;To use PWM in the software, the Arduino core code provides the &lt;code&gt;analogWrite&lt;/code&gt; method. It has two arguments: 1) the pin number; and 2) the duty cycle value, expressed as a number between 0 (only LOW signal for the whole period) and 255 (only HIGH signal for the whole period). Notice that hardware wise, it is possible to have more than 8 bit (thus, values from 0 to 255) PWM resolution, since some of the PWM pins are 16 bit PWM resolution capable. The number of bits defines the granularity of the duty cycle.&lt;/p&gt;

&lt;p&gt;The pulse frequency is different from board to board and from pin to pin. For example, Arduino UNO uses a frequency of 980Hz for PWM pins 5 and 6 and about 490Hz for the other PWM pins (i.e., 3, 9, 10, 11).&lt;/p&gt;

&lt;p&gt;Lets now play with our LED and try to obtain all the color combinations we can get for 8 bit resolution. For this will loop each LED through each 5th PWM value, at an interval of 8 milliseconds, thus at about 125Hz so our eyes does not perceive the breaks. 30Hz suffices for our eyes, but then the change in color will be to slow and you need quite long time to see all the variations. The total run time, for every 5th PWM value, three PWM pins and 125Hz changing frequency on the most variable color (that&#039;s red in our case), is between 15 and 20 minutes.&lt;/p&gt;

&lt;pre&gt;
void setup() {
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}
void loop() {
  for (uint8_t i = 0; i &amp;lt; 250; i+=5) {
    analogWrite(9, i);
    for (uint8_t j = 0; j &amp;lt; 250; j+=5) {
      analogWrite(10, j);
      for (uint8_t k = 0; k &amp;lt; 250; k+=5) {
        analogWrite(11, k);
        delay(8);
      }
    }
  }
}&lt;/pre&gt;

&lt;p&gt;PWM does not represent a complete replacement for DACs, but is a solution when such (in general more expensive) modules are not available.&lt;/p&gt;

&lt;h2&gt;Some Points of Attention&lt;/h2&gt;

&lt;p&gt;While in this tutorial we only &quot;played&quot; with (RGB) LEDs, and just had some simple operations, we&#039;ve gone through an important set of basic Arduino capabilities. Some other more advanced features, such as analog input or communication protocols (SPI, I2C, etc) are part of the future tutorials.&lt;/p&gt;

&lt;p&gt;We brought in discussion only the Arduino UNO and Nano boards, but the above shown code will work with most of the Arduino boards without any modification. However, it is important to know that some Arduino boards, such as Arduino DUE, uses 3.3V as input (&lt;code&gt;VCC = 3V&lt;/code&gt;). Therefore, the appropriate resistor values need to be recalculated. Also, some boards have a lower maximum current value per pin, e.g., Arduino DUE allows a maximum of 3mA or 15mA per pin, depending on the used pin.&lt;/p&gt;

&lt;p&gt;In our code examples, the explicit number of the Arduino board pin was used. While this is easy to do with small programs, it becomes more and more difficult when your code grows. In such cases, but not only, since this is a kind of general recommendation, it is good to use constants. For example, instead of using 9 to identify the pin used to control the blue LED, we could have used a constant BLUE_LED, as shown in the example below:&lt;/p&gt;

&lt;pre&gt;
const uint8_t BLUE_LED = 9;

void setup() {
  pinMode(BLUE_LED, OUTPUT);
}
&lt;/pre&gt;

&lt;p&gt;Or even better, we can use the &lt;code&gt;#define&lt;/code&gt; directive to obtain at compile time a replacement of all the identifier occurrences with the corresponding value:&lt;/p&gt;

&lt;pre&gt;
#define BLUE_LED 9;

void setup() {
  pinMode(BLUE_LED, OUTPUT);
}
&lt;/pre&gt;

&lt;p&gt;Using the &lt;code&gt;#define&lt;/code&gt; directive has the advantage that it does not take extra static memory. Learn more about how to deal with Arduino limited RAM resources: &lt;a href=&quot;http://web-engineering.info/node/30&quot;&gt;Optimize Arduino Memory Usage&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This is not only a better programming style, but also allows to easily change the pin without a need to replace the pin number in multiple place of your code. We have used explicit pin numbers so one can make the relation between what is written on the Arduino board near each pin, and what you see in the code. However, starting from now on we&#039;ll use constants instead of &quot;magic pin numbers&quot;.&lt;/p&gt;

&lt;h2&gt;Next Tutorial: Part 2 - Sensing with Analog and Digital Sensors&lt;/h2&gt;

&lt;p&gt;In the second part, we&#039;ll learn how to use various digital and analog sensors with an Arduino board. Specifically, we discuss the DHT22 (temperature and humidity digital sensor), the Grove (soil moisture analog sensor), PIR (passive infrared digital sensor) and HC-SR04 (ultrasonic distance measurement digital sensor). The release date of the second part is: before 21 April 2016.&lt;/p&gt;
&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;section class=&quot;field field-name-field-category field-type-taxonomy-term-reference field-label-above view-mode-rss&quot;&gt;&lt;h2 class=&quot;field-label&quot;&gt;Category:&amp;nbsp;&lt;/h2&gt;&lt;ul class=&quot;field-items&quot;&gt;&lt;li class=&quot;field-item even&quot;&gt;&lt;a href=&quot;/Arduino&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;Arduino&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item odd&quot;&gt;&lt;a href=&quot;/taxonomy/term/40&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;WoT&lt;/a&gt;&lt;/li&gt;&lt;li class=&quot;field-item even&quot;&gt;&lt;a href=&quot;/taxonomy/term/43&quot; typeof=&quot;skos:Concept&quot; property=&quot;rdfs:label skos:prefLabel&quot; datatype=&quot;&quot;&gt;C/C++&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/section&gt;&lt;div class=&quot;easy_social_box clearfix horizontal easy_social_lang_und&quot;&gt;
            &lt;div class=&quot;easy_social-widget easy_social-widget-twitter first&quot;&gt;&lt;a href=&quot;http://twitter.com/share&quot; class=&quot;twitter-share-button&quot;
data-url=&quot;https://web-engineering.info/node/60&quot;
data-count=&quot;horizontal&quot;
data-lang = &quot;en&quot;
data-via=&quot;&quot;
data-related=&quot;:Check it out!&quot;
data-text=&quot;WoT with Arduino for Beginners: Part 1 - Mastering the RGB LED&quot;&gt;Tweet&lt;/a&gt;&lt;/div&gt;
          &lt;div class=&quot;easy_social-widget easy_social-widget-facebook&quot;&gt;&lt;fb:like href=&quot;https://web-engineering.info/node/60&quot; send=&quot;true&quot; layout=&quot;button_count&quot; width=&quot;88&quot; show_faces=&quot;true&quot; action=&quot;like&quot; colorscheme=&quot;light&quot; font=&quot;&quot;&gt;&lt;/fb:like&gt;&lt;/div&gt;
          &lt;div class=&quot;easy_social-widget easy_social-widget-googleplus&quot;&gt;&lt;div class=&quot;g-plusone&quot; data-size=&quot;medium&quot; data-annotation=&quot;bubble&quot; data-href=&quot;https://web-engineering.info/node/60&quot;&gt;&lt;/div&gt;&lt;/div&gt;
          &lt;div class=&quot;easy_social-widget easy_social-widget-linkedin last&quot;&gt;&lt;script type=&quot;in/share&quot; data-url=&quot;https://web-engineering.info/node/60&quot; data-counter=&quot;right&quot;&gt;&lt;/script&gt;&lt;/div&gt;
  &lt;/div&gt; &lt;!-- /.easy_social_box --&gt;</description>
 <pubDate>Mon, 04 Apr 2016 13:07:40 +0000</pubDate>
 <dc:creator>mdiaconescu</dc:creator>
 <guid isPermaLink="false">60 at https://web-engineering.info</guid>
 <comments>https://web-engineering.info/node/60#comments</comments>
</item>
</channel>
</rss>
