<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ arduino - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ arduino - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 09 May 2026 14:06:03 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/arduino/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Use Arduinos for Computer Vision ]]>
                </title>
                <description>
                    <![CDATA[ We just published a new course on the freeCodeCamp.org YouTube channel that mixes computer vision, deep learning, and Arduino into some really fun projects. In this course, you’ll build two hands-on applications using MediaPipe and OpenCV. The first ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-arduinos-for-computer-vision/</link>
                <guid isPermaLink="false">68ae60dd2ebe767204ec0f59</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Wed, 27 Aug 2025 01:35:25 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756258472163/30bdd66e-4458-4c70-b596-20685e993d37.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>We just published a new course on the freeCodeCamp.org YouTube channel that mixes computer vision, deep learning, and Arduino into some really fun projects.</p>
<p>In this course, you’ll build two hands-on applications using MediaPipe and OpenCV. The first project shows you how to control an LCD display with your facial movements. The second project takes things further by using computer vision to control a robotic arm.</p>
<p>Along the way, you’ll learn how to:</p>
<ul>
<li><p>Set up serial communication between Python and Arduino</p>
</li>
<li><p>Use MediaPipe’s face detection and landmarks module</p>
</li>
<li><p>Work with LCD displays and servo motors</p>
</li>
<li><p>Apply image processing techniques with OpenCV</p>
</li>
</ul>
<p>The instructor, Yılmaz ALACA, walks you through the process step by step and explains the hardware and software in a clear way.</p>
<p>You can watch the full course <a target="_blank" href="https://youtu.be/Q5U-b6gRTaY">on the freeCodeCamp.org YouTube channel</a> (3-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Q5U-b6gRTaY" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use a Resistive Soil Moisture Sensor ]]>
                </title>
                <description>
                    <![CDATA[ A resistive soil moisture sensor is a widely used, simple, and affordable way of estimating the amount of water in the soil. In this tutorial, you will learn how to interface a resistive soil moisture sensor with an Arduino UNO microcontroller. You w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-a-resistive-soil-moisture-sensor/</link>
                <guid isPermaLink="false">686f06fb2134825dffc4a228</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Michael Ikoko ]]>
                </dc:creator>
                <pubDate>Thu, 10 Jul 2025 00:19:07 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752106699262/6ae871df-e1fb-4019-a446-9bd8cca1cab0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A resistive soil moisture sensor is a widely used, simple, and affordable way of estimating the amount of water in the soil.</p>
<p>In this tutorial, you will learn how to interface a resistive soil moisture sensor with an Arduino UNO microcontroller. You will learn about the parts and components of the sensor, how to calibrate the sensor for your soil type, and how to read both analog and digital output data from the sensor.</p>
<p>You will implement two practical examples in this tutorial:</p>
<ol>
<li><p>The first example illustrates how you can read the analog output data from the sensor and convert the analog reading to a percentage value.</p>
</li>
<li><p>The second example illustrates how you can use the digital output from the sensor to determine if the soil is wet or dry, and indicate the result using a red and green LED.</p>
</li>
</ol>
<p>At the end of the tutorial, you will have a solid understanding of how a resistive soil moisture sensor works and how to integrate the sensor into your microcontroller-based projects.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To effectively follow along with this tutorial, you should have the following components:</p>
<ul>
<li><p>Arduino UNO</p>
</li>
<li><p>Resistive Soil Moisture Sensor</p>
</li>
<li><p>Breadboard</p>
</li>
<li><p>5 LEDs (any color for the analog example)</p>
</li>
<li><p>1 red LED and 1 green LED (for the digital example)</p>
</li>
<li><p>220-ohm resistors (one per LED)</p>
</li>
<li><p>Jumper wires</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-soil-moisture-sensor">What is a Soil Moisture Sensor?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-soil-moisture-sensors">Types of Soil Moisture Sensors</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-parts-of-a-resistive-soil-moisture-sensor">Parts of a Resistive Soil Moisture Sensor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-calibrate-the-sensor-for-your-soil">How to Calibrate the Sensor for Your Soil</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-1-how-to-determine-soil-moisture-level-in-percentage-from-analog-output">Example 1: How to Determine Soil Moisture Level in Percentage from Analog Output</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-2-how-to-determine-soil-moisture-state-from-digital-output">Example 2: How to Determine Soil Moisture State from Digital Output</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-soil-moisture-sensor">What is a Soil Moisture Sensor?</h2>
<p>A soil moisture sensor is a device that estimates the moisture content in the soil. Soil moisture sensors typically operate by measuring the soil's electrical properties, such as dielectric and resistance. Some soil moisture sensors also use time domain methods to determine the propagation speed of electromagnetic waves through the soil.</p>
<p>Soil moisture sensors have various applications in different fields. These applications include, but are not limited to:</p>
<ul>
<li><p>Climate and environmental research</p>
</li>
<li><p>Automated/smart irrigation system</p>
</li>
<li><p>Greenhouse monitoring systems</p>
</li>
<li><p>Urban planning</p>
</li>
</ul>
<h2 id="heading-types-of-soil-moisture-sensors">Types of Soil Moisture Sensors</h2>
<p>Soil moisture sensors are categorized based on the property of the soil that they measure as an indicator of the moisture content. The most common soil moisture sensors for small-scale projects are:</p>
<ul>
<li><p>Resistive soil moisture sensors</p>
</li>
<li><p>Capacitive soil moisture sensors</p>
</li>
</ul>
<h3 id="heading-resistive-soil-moisture-sensor">Resistive Soil Moisture Sensor</h3>
<p>A resistive soil moisture sensor estimates the moisture content based on the relationship between water content and soil resistivity. The electrical resistivity of the soil reduces exponentially as the water content increases.</p>
<p>The resistive soil moisture sensor has two probes inserted into the soil. It measures the electrical resistance of the soil between the two probes.</p>
<h3 id="heading-capacitive-soil-moisture-sensor">Capacitive Soil Moisture Sensor</h3>
<p>A capacitive soil moisture sensor determines the moisture content of the soil based on the relationship between water content and the dielectric properties of the soil. The dielectric constant of a soil increases as the water content increases.</p>
<p>A capacitive soil moisture sensor typically has a positive plate and a negative plate with space between them. When inserted into the soil, the soil becomes the dielectric medium between both plates. The sensor measures the change in the soil's dielectric property.</p>
<h3 id="heading-how-to-choose-between-resistive-and-capacitive-sensors">How to Choose Between Resistive and Capacitive Sensors</h3>
<p>The choice between a resistive and capacitive soil moisture sensor depends on a couple of factors:</p>
<ul>
<li><p><strong>Cost</strong>: A resistive soil moisture sensor is typically less expensive than a capacitive sensor.</p>
</li>
<li><p><strong>Accuracy</strong>: Capacitive soil moisture sensors are more accurate than their resistive counterparts. Factors like soil type and application of fertilizers have a lesser effect on the sensitivity of the capacitive soil moisture sensor.</p>
</li>
<li><p><strong>Long-term use</strong>: Resistive soil moisture sensors are prone to corrosion with frequent use. This happens because the current flowing through the probes in contact with the soil causes electrolysis of the metal electrodes in the probes. On the other hand, capacitive soil moisture sensors are resistant to corrosion. This is because the contact plates are embedded in corrosion-resistant materials and don't need to be in direct contact with the soil.</p>
</li>
</ul>
<h2 id="heading-parts-of-a-resistive-soil-moisture-sensor">Parts of a Resistive Soil Moisture Sensor</h2>
<p>The resistor soil moisture sensor module is usually made of two parts: the sensor probes and the voltage comparator module.</p>
<h3 id="heading-the-sensor-probes">The Sensor Probes</h3>
<p>The probes are the part of the sensor that is placed in the soil. The probes are used to detect the electrical resistance across two points in the soil.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909048810/7c2367b5-872c-4e98-acf8-d8b2f0851f6c.jpeg" alt="Sensor probes labelled diagram" class="image--center mx-auto" width="2048" height="1152" loading="lazy"></p>
<p>As shown in the diagram above, the sensor probes have the following components:</p>
<ul>
<li><p><strong>Electrodes</strong>: The metal electrodes conduct current through the soil. When the sensor is powered, current flows from one electrode through the soil to the other electrode and back to the comparator module. The sensor then measures the soil's resistance to the electrical signal flowing through the soil across the electrodes to determine the moisture level.</p>
</li>
<li><p><strong>Non-polarized connector pins</strong>: The two connector pins are used to connect the probes to the voltage comparator module. The pins have no polarity and can be connected in any order to the respective connector pins on the voltage comparator module. The probe is connected to the comparator module using female-to-female jumper wires.</p>
</li>
</ul>
<h3 id="heading-the-voltage-comparator-module">The Voltage Comparator Module</h3>
<p>The voltage comparator module interprets the electrical signal from the probes, processes the signals, and provides both analog and digital outputs that can be read by the microcontroller.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909173338/454ae6bf-2d34-4131-af88-c990eb988cbd.jpeg" alt="Sensor voltage comparator module labelled diagram" class="image--center mx-auto" width="2048" height="1152" loading="lazy"></p>
<p>The voltage comparator module has the following components:</p>
<ul>
<li><p><strong>LM393 Comparator Chip</strong>: The LM393 comparator is a dual comparator that compares the electrical signal from the probes to a reference set by the potentiometer and produces a digital output. The reference signal corresponds to a certain soil moisture level (threshold) and is set using the potentiometer.</p>
<ul>
<li><p>The comparator outputs a <code>HIGH</code> when the analog signal read from the probes is above the reference, this means the soil has less moisture than the threshold moisture level.</p>
</li>
<li><p>The comparator outputs a <code>LOW</code> when the analog signal read from the probes is less than the reference; this means the soil has more moisture than the threshold moisture level.</p>
</li>
</ul>
</li>
<li><p><strong>Potentiometer</strong>: The potentiometer is used to set the reference electrical signal that is used by the LM393 comparator chip. The potentiometer raises or lowers the threshold moisture level. It consists of a knob that can be turned either clockwise or counterclockwise.</p>
</li>
<li><p><strong>Power Indicator (PWR-LED)</strong>: The power indicator is an LED that turns on when the module is powered on.</p>
</li>
<li><p><strong>Digital Output Indicator (DO-LED)</strong>: The digital output indicator is an LED that turns on when the sensor detects wet soil. That is, the current moisture level read from the sensor is above the threshold, and the comparator outputs a <code>LOW</code>.</p>
</li>
<li><p><strong>Power Supply Pin (VCC)</strong>: This pin is used to supply power to the sensor. The sensor module can be powered by a 5V or 3.3V voltage source. You should note that changing the voltage source also changes the analog output from the sensor. In this tutorial, you will be using one of the digital pins to power the sensor. The digital pins of the Arduino output 5V. The sensor typically has an operating current of 15mA, and the Arduino digital output pin can provide a maximum current of 40mA, so it can safely power the sensor.</p>
</li>
<li><p><strong>Ground Pin (GND)</strong>: This pin is used to provide a ground reference for the sensor. It is usually connected to any ground pin in your microcontroller.</p>
</li>
<li><p><strong>Digital Output Pin (DO)</strong>: The digital output pin outputs a <code>HIGH</code> or a <code>LOW</code> based on the value obtained from the LM393 comparator. This pin is usually used by a microcontroller to read the digital output of the LM393 comparator.</p>
</li>
<li><p><strong>Analog Output Pin (AO)</strong>: The analog output pin provides a 10-bit analog voltage value. The values range from 0 to 1023, and they indicate the moisture level of the soil. Typically, in most sensors, higher analog values indicate drier soil and lower analog values indicate wetter soil.</p>
</li>
<li><p><strong>Sensor Probe Connector Pins</strong>: These two pins are used to connect the sensor probes to the voltage comparator module.</p>
</li>
</ul>
<h2 id="heading-how-to-calibrate-the-sensor-for-your-soil">How to Calibrate the Sensor for Your Soil</h2>
<p>As explained earlier in the article, the resistive soil moisture sensor is sensitive to soil type. This means that it’s important that you calibrate the sensor to the soil type you intend to use it on. You do this to improve the accuracy of your readings on a particular soil.</p>
<p>One way of calibrating the sensor is to determine the possible range of values for the soil type. That means you measure the sensor's output when the soil is totally dry and when the soil is totally wet. You can then use this range of values to map the sensor's reading to a new scale, like a percentage. The following steps describe how you can calibrate the sensor:</p>
<h3 id="heading-step-1-connect-the-sensor-to-the-arduino">Step 1: Connect the Sensor to the Arduino</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909238974/d84a8df3-52d0-4f5e-90a4-9a4fa6c198fb.jpeg" alt="Schematic diagram for soil calibration" class="image--center mx-auto" width="1393" height="1553" loading="lazy"></p>
<p>Using the image above as a reference, connect the sensor to the Arduino microcontroller as follows:</p>
<ol>
<li><p>Connect the <strong>VCC</strong> or <strong>Power</strong> pin of the sensor's module to digital pin <strong>7</strong> of the Arduino. This allows you to control the supply voltage to the sensor in the Arduino sketch, ensuring that the sensor is only powered when you want to take a reading. Doing this can help improve the durability of the sensor.</p>
</li>
<li><p>Connect the <strong>GND</strong> pin of the sensor's module to a ground pin in the microcontroller.</p>
</li>
<li><p>Connect the analog output pin <strong>AO</strong> of the sensor's module to the analog pin <strong>A0</strong> of the Arduino. This is the pin where you will read the analog data from the sensor.</p>
</li>
<li><p>Connect the two pins on the probes to the two connector pins on the sensor's module. The connector pins have no polarity.</p>
</li>
</ol>
<h3 id="heading-step-2-upload-calibration-sketch-to-microcontroller">Step 2: Upload Calibration Sketch to Microcontroller</h3>
<p>Upload the following sketch into the Arduino:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sensorPin = A0; <span class="hljs-comment">// Analog input pin for sensor</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> powerPin = <span class="hljs-number">7</span>; <span class="hljs-comment">// Digital pin to power the sensor</span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getAverageReading</span><span class="hljs-params">(<span class="hljs-keyword">int</span> analogPin, <span class="hljs-keyword">int</span> powerPin, <span class="hljs-keyword">int</span> samples = <span class="hljs-number">10</span>)</span> </span>{
  <span class="hljs-keyword">long</span> total = <span class="hljs-number">0</span>;

  digitalWrite(powerPin, HIGH); <span class="hljs-comment">// Power ON sensor</span>
  delay(<span class="hljs-number">500</span>); <span class="hljs-comment">// Wait for sensor to stabilize</span>

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; samples; i++) {                    
 total += analogRead(analogPin);
    delay(<span class="hljs-number">10</span>); <span class="hljs-comment">// Short gap between cycles</span>
 }

  digitalWrite(powerPin, LOW); <span class="hljs-comment">// Power OFF sensor</span>
  <span class="hljs-keyword">return</span> total / samples;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);

  pinMode(powerPin, OUTPUT);
  digitalWrite(powerPin, LOW); <span class="hljs-comment">// Ensure sensor is off at start</span>

  Serial.println(<span class="hljs-string">"Calibration mode: Insert into DRY or WET soil and observe values."</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> avgReading = getAverageReading(sensorPin, powerPin, <span class="hljs-number">20</span>); <span class="hljs-comment">// Take 20 averaged samples</span>
  Serial.print(<span class="hljs-string">"Average analog reading: "</span>);
  Serial.println(avgReading);
  delay(<span class="hljs-number">2000</span>); <span class="hljs-comment">// Update every 2 seconds</span>
}
</code></pre>
<p>In the sketch, you begin by defining the pins for powering the sensor and reading the analog data from the sensor. The digital pin <code>7</code> powers the sensor, and the analog pin <code>A0</code> reads data from the sensor.</p>
<p>The <code>getAverageReading</code> function powers on the sensor, takes multiple readings from the sensor, powers off the sensor, and returns the average of the readings taken. The function has three parameters:</p>
<ul>
<li><p><code>analogPin</code> – The analog input pin, which reads data from the sensor to the microcontroller.</p>
</li>
<li><p><code>powerPin</code> – The pin used to power the sensor. The sensor is powered only when you want to take a reading.</p>
</li>
<li><p><code>samples</code> – The number of readings taken from the sensor. This defaults to <code>10</code>. You take multiple readings as a way of filtering out noise in the sensor data.</p>
</li>
</ul>
<p>In the <code>setup</code> function, you begin by setting the baud rate, which is <code>9600</code> for Arduino UNO and differs across different microcontrollers. Then you set the digital pin <code>7</code> used to power the sensor as an output pin, and write a <code>LOW</code> to the sensor to ensure it is off at the start.</p>
<p>Lastly, in the <code>loop</code> function, you get the average analog reading from the <code>getAverageReading</code> function and print it to the Serial Monitor. You should note that in the sketch, the readings are taken every 2 seconds – this delay should be longer in a practical application in order to improve the durability of the sensor.</p>
<h3 id="heading-step-3-record-the-value-for-dry-soil">Step 3: Record the Value for Dry Soil</h3>
<p>Insert the sensor's probe into a completely dry soil sample, and record the average analog reading. You can dry the soil by baking it in an oven to remove moisture. Note that you must allow the soil to cool before inserting the sensor's probe. Hot soil may damage the sensor. The analog readings from the sensor differ according to soil type but are typically very high for dry soil. This is what I obtained for a dry soil sample:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909305339/35d99200-d169-4419-9292-e54a9c544d77.png" alt="Serial monitor showing analog reading for dry soil" class="image--center mx-auto" width="1368" height="738" loading="lazy"></p>
<h3 id="heading-step-4-record-the-value-for-wet-soil">Step 4: Record the Value for Wet Soil</h3>
<p>Insert the sensor's probe into a completely wet soil sample, and record the average analog reading. The value is typically low when the soil is saturated. This is what I obtained for a wet soil sample:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909623291/5478b034-ce56-4f9b-a6d7-758508eb0c1a.png" alt="Serial monitor showing analog reading for wet soil" class="image--center mx-auto" width="1370" height="738" loading="lazy"></p>
<p>You will use these recorded analog values for wet and dry soil in the subsequent section as reference points to map future readings onto a percent scale. In the example provided later in this tutorial, the moisture level is expressed as a percentage, between 0%(dry) and 100%(wet). Using the calibration values ensures that the percentage output accurately reflects the conditions of your soil type.</p>
<h2 id="heading-example-1-how-to-determine-soil-moisture-level-in-percentage-from-analog-output">Example 1 – How to Determine Soil Moisture Level in Percentage from Analog Output</h2>
<p>In this example, you will learn how to read the analog data from the soil moisture sensor, convert the analog reading to a percentage value, and visually represent the moisture level using five LEDs.</p>
<p>The analog reading from the sensor is inversely proportional to the soil moisture level. This means that higher analog readings indicate drier soil and lower readings indicate wetter soil.</p>
<p>The LEDs act as a visual indicator of the moisture percentage. The LEDs are lit based on a range of soil moisture levels:</p>
<ul>
<li><p>1 LED: 0-20% (very dry)</p>
</li>
<li><p>2 LEDs: 20-40%</p>
</li>
<li><p>3 LEDs: 40-60%</p>
</li>
<li><p>4 LEDs: 60-80%</p>
</li>
<li><p>5 LEDs: 80-100% (very wet)</p>
</li>
</ul>
<h3 id="heading-circuit-diagram">Circuit Diagram</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909722810/0aff204d-2ddd-44d5-80b5-5765b9cf5fe9.jpeg" alt="Circuit diagram for Example 1" class="image--center mx-auto" width="1797" height="1893" loading="lazy"></p>
<p>Using the schematic above as a reference, design the circuit as follows:</p>
<ol>
<li><p>Connect the sensor to the Arduino in the same way as described in the calibration section. That is, connect the sensor's power pin (VCC) to digital pin 7, analog output pin <strong>AO</strong> to analog pin <strong>A0</strong>, and ground pin to any ground pin of the microcontroller.</p>
</li>
<li><p>Connect each of the LEDs in series with a 220-ohm resistor.</p>
</li>
<li><p>Connect the anode of the five LEDs to digital pins 3, 4, 5, 6, and 8 of the microcontroller.</p>
</li>
</ol>
<p>This is how my setup looked:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909770251/226bd848-2a58-4e2f-9bf4-796a54983d47.jpeg" alt="Physical setup for Project 1" class="image--center mx-auto" width="1561" height="1688" loading="lazy"></p>
<h3 id="heading-arduino-code">Arduino Code</h3>
<p>Upload the following sketch to your Arduino:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sensorPin = A0; <span class="hljs-comment">// Analog input from soil moisture sensor</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> powerPin = <span class="hljs-number">7</span>; <span class="hljs-comment">// Digital pin to power the sensor</span>

<span class="hljs-comment">// LED bar pins (from lowest to highest)</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> ledPins[<span class="hljs-number">5</span>] = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>};

<span class="hljs-comment">// Calibrated analog values - replace with your values</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> dryValue = <span class="hljs-number">1005</span>;
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> wetValue = <span class="hljs-number">254</span>;

<span class="hljs-comment">// Global to hold the last analog value</span>
<span class="hljs-keyword">int</span> lastAnalogReading = <span class="hljs-number">0</span>;

<span class="hljs-comment">// Read and calculate soil moisture percentage</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getMoisturePercent</span><span class="hljs-params">(<span class="hljs-keyword">int</span> analogPin, <span class="hljs-keyword">int</span> powerPin, <span class="hljs-keyword">int</span> samples = <span class="hljs-number">10</span>)</span> </span>{
  <span class="hljs-keyword">unsigned</span> <span class="hljs-keyword">long</span> total = <span class="hljs-number">0</span>;

  digitalWrite(powerPin, HIGH);
  delay(<span class="hljs-number">10</span>); <span class="hljs-comment">// Allow sensor to stabilize</span>

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; samples; i++) {
 total += analogRead(analogPin);
    delay(<span class="hljs-number">10</span>);
 }

  digitalWrite(powerPin, LOW);

  <span class="hljs-keyword">int</span> avgReading = total / samples;
 lastAnalogReading = avgReading;

  <span class="hljs-keyword">int</span> percent = <span class="hljs-built_in">map</span>(avgReading, dryValue, wetValue, <span class="hljs-number">0</span>, <span class="hljs-number">100</span>);
  <span class="hljs-keyword">return</span> constrain(percent, <span class="hljs-number">0</span>, <span class="hljs-number">100</span>);
}

<span class="hljs-comment">// Update LED states using boolean array</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">updateLEDBar</span><span class="hljs-params">(<span class="hljs-keyword">int</span> percent)</span> </span>{
  <span class="hljs-keyword">bool</span> ledStates[<span class="hljs-number">5</span>] = {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>}; <span class="hljs-comment">// Default all OFF</span>

  <span class="hljs-keyword">if</span> (percent &lt;= <span class="hljs-number">20</span>) {
    ledStates[<span class="hljs-number">0</span>] = <span class="hljs-literal">true</span>;
 } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (percent &lt;= <span class="hljs-number">40</span>) {
    ledStates[<span class="hljs-number">0</span>] = ledStates[<span class="hljs-number">1</span>] = <span class="hljs-literal">true</span>;
 } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (percent &lt;= <span class="hljs-number">60</span>) {
    ledStates[<span class="hljs-number">0</span>] = ledStates[<span class="hljs-number">1</span>] = ledStates[<span class="hljs-number">2</span>] = <span class="hljs-literal">true</span>;
 } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (percent &lt;= <span class="hljs-number">80</span>) {
    ledStates[<span class="hljs-number">0</span>] = ledStates[<span class="hljs-number">1</span>] = ledStates[<span class="hljs-number">2</span>] = ledStates[<span class="hljs-number">3</span>] = <span class="hljs-literal">true</span>;
 } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) ledStates[i] = <span class="hljs-literal">true</span>;
 }

 <span class="hljs-comment">// Write LED states to pins</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
    digitalWrite(ledPins[i], ledStates[i] ? HIGH : LOW);
 }
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  pinMode(sensorPin, INPUT);
  pinMode(powerPin, OUTPUT);
  digitalWrite(powerPin, LOW); <span class="hljs-comment">// Start with sensor powered off</span>

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) {
    pinMode(ledPins[i], OUTPUT);
    digitalWrite(ledPins[i], LOW); <span class="hljs-comment">// Ensure all LEDs start OFF</span>
 }

  Serial.println(<span class="hljs-string">"Soil Moisture Monitor with 5-LED Bar (Boolean Array)"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> moisturePercent = getMoisturePercent(sensorPin, powerPin, <span class="hljs-number">20</span>);

 <span class="hljs-comment">// Print both analog reading and percent</span>
  Serial.print(<span class="hljs-string">"Analog Reading: "</span>);
  Serial.print(lastAnalogReading);
  Serial.print(<span class="hljs-string">"  |  Moisture: "</span>);
  Serial.print(moisturePercent);
  Serial.println(<span class="hljs-string">" %"</span>);

  updateLEDBar(moisturePercent);

  delay(<span class="hljs-number">2000</span>); <span class="hljs-comment">// Update every 2 seconds</span>
}
</code></pre>
<p>In the sketch, you start by defining the analog pin for reading data from the sensor and the digital pin for powering the sensor. You also define the following variables, which will be used in the code:</p>
<ul>
<li><p><code>ledPins[5]</code> – An array that stores the digital pins used to power each LED. The pins are arranged from the first LED to the last one. That is the visual display order from left to right.</p>
</li>
<li><p><code>dryValue</code> – This variable stores the analog value recorded for dry soil during the calibration section.</p>
</li>
<li><p><code>wetValue</code> – This variable stores the analog value recorded for wet soil during the calibration section.</p>
</li>
<li><p><code>lastAnalogReading</code> – This variable stores the last reading taken by the sensor. You use this variable to log the actual analog reading to the Serial Monitor.</p>
</li>
</ul>
<p>The <code>getMoisturePercent</code> function powers on the sensor, takes multiple readings, powers off the sensor, calculates the average analog reading, represents the analog reading in percent, and returns the percent value. The function also saves the average analog reading to the <code>lastAnalogReading</code> variable. You can print it directly here, but this sketch saves it in a separate variable so that you can print it later in the <code>loop</code> function for readability.</p>
<p>You can express the average analog reading in percentage with the <code>map(avgReading, dryValue, wetValue, 0, 100)</code> function. The function remaps the average reading stored in <code>avgReading</code> from the range of your calibration values <code>dryValue</code> and <code>wetValue</code> to a new range between <code>0</code> and <code>100</code> (where <code>0</code> is the driest and <code>100</code> is the wettest). You then use the <code>constrain</code> function to keep values within the <code>0</code> and <code>100</code> range.</p>
<p>The <code>updateLEDBar</code> function displays the percent value using the LEDs. The <code>ledStates</code> array in the function stores the logic state of each LED. You begin by setting all LEDs off – that is, having a state <code>0</code>. The next bit of logic is a simple <code>if</code> statement where you turn on the required LEDs corresponding to a particular percent range by setting the elements in the array to <code>true</code> (equivalent to <code>1</code>). You end the function by writing the states in the <code>ledStates</code> to the pins in <code>ledPins</code>.</p>
<p>The <code>setup</code> function is pretty routine: you set the baud rate for serial communication, define input and output digital pins, and write a <code>LOW</code> to the digital output pins to ensure they are all turned off at the start.</p>
<p>In the <code>loop</code> function, you call the <code>getMoisturePercent</code> function to get the percent moisture value. You then print the percent value and the average analog reading to the Serial Monitor for clarity. Lastly, you call the <code>updateLEDBar</code> function with the percent value as a parameter to turn on the respective LEDs to indicate the moisture level.</p>
<h3 id="heading-test-the-system">Test the System</h3>
<p>You can proceed to test the example with different moisture levels. For example:</p>
<ul>
<li>At around a 37% moisture level, two LEDs are lit.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909854736/5312e441-d9fd-498f-bd87-b902231b27f4.jpeg" alt="Test example 1 with 37% moisture level" width="2106" height="738" loading="lazy"></p>
<ul>
<li>At about a 76% moisture level, four LEDs are lit.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909910096/eabf2f8d-7499-4c6a-be49-74d4c8a3da30.jpeg" alt="Test example 1 with 76% moisture level" width="2108" height="738" loading="lazy"></p>
<p>You can also simulate the example on Tinkercad here: <a target="_blank" href="https://www.tinkercad.com/embed/6s47ZvIrNOP">https://www.tinkercad.com/embed/6s47ZvIrNOP</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752100775640/12f92988-7697-4069-9068-86f663b20794.png" alt="Example 1 Tinkercad simulation image" class="image--center mx-auto" width="1366" height="615" loading="lazy"></p>
<h2 id="heading-example-2-how-to-determine-soil-moisture-state-from-digital-output">Example 2 – How to Determine Soil Moisture State from Digital Output</h2>
<p>In the previous project, you learned how to read the analog data from the sensor and convert the value into a percentage. If your application requires a binary output, you can use the digital output pin. In this section, you'll learn how to use the digital output pin of the sensor.</p>
<p>The digital output pin has only two states:</p>
<ul>
<li><p><code>LOW</code> – This state corresponds to 0V and is the output when the soil is wet, that is, the moisture level is above the set threshold.</p>
</li>
<li><p><code>HIGH</code> – This state corresponds to 5V and is the output when the soil is dry, that is, the moisture level is below the threshold moisture level.</p>
</li>
</ul>
<h3 id="heading-circuit-diagram-1">Circuit Diagram</h3>
<p>The example built in this section is very simple. It consists of a red and green LED. When the sensor outputs a <code>LOW</code> from the digital output pin, which means the soil is wet, the green LED turns on. When the sensor outputs a <code>HIGH</code> from the digital output pin, which means the soil is dry, the red LED turns on.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751909967743/761e3422-ad95-4f8e-9b4d-4963970c926e.jpeg" alt="Circuit diagram for example 2" width="1987" height="1826" loading="lazy"></p>
<p>Using the circuit diagram above as a reference, design the circuit as follows:</p>
<ol>
<li><p>Place the sensor module on the breadboard.</p>
</li>
<li><p>As in the previous project, connect the power (VCC) pin of the sensor module to digital pin 7 of the microcontroller, and the ground (GND) pin to a ground pin on the microcontroller.</p>
</li>
<li><p>Connect the digital output (DO) pin of the sensor to digital pin 2 of the microcontroller. This pin is where you will read the data from the sensor.</p>
</li>
<li><p>Connect the red and green LEDs each to a 220-ohm resistor in series.</p>
</li>
<li><p>Connect the anode of the red and green LEDs to digital pins 12 and 13 of the microcontroller, respectively.</p>
</li>
</ol>
<p>This is how my physical connection looked:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751910000801/55382b8f-cdd4-4f85-9b6a-342af252329b.jpeg" alt="Physical setup for example 2" width="1400" height="1100" loading="lazy"></p>
<h3 id="heading-how-to-set-the-threshold-moisture-level">How to Set the Threshold Moisture Level</h3>
<p>Before using the digital output pin of the soil sensor module, you first have to set a threshold moisture level.</p>
<p>The sensor's module has a built-in potentiometer that allows you to adjust the moisture level, which will be used as a threshold. The sensor also has a built-in LM393 comparator, which continuously compares the actual reading from the sensor to the threshold set by the potentiometer and outputs the appropriate state.</p>
<p>You can set the threshold moisture level by rotating the knob on the potentiometer. Rotating the potentiometer clockwise lowers the threshold. Rotating the potentiometer counterclockwise raises the threshold. The sensor module also has a built-in LED labeled <strong>DO-LED</strong> that turns on when the sensor output is <code>LOW</code>. Set the threshold as follows:</p>
<ol>
<li><p>Place the sensor's probe in soil just dry enough that it requires irrigation. That is the soil whose moisture level you want to use as a threshold. Note that the DO-LED should be off.</p>
</li>
<li><p>Use a small screwdriver to rotate the potentiometer clockwise until the DO-LED comes on. Turning clockwise reduces the threshold level until it is slightly lower than the current moisture level, thereby triggering the digital output indicator (DO-LED) to turn on.</p>
</li>
<li><p>Turn the screw slightly counterclockwise just enough to turn the built-in digital LED off. Given that the current moisture level of the soil is dry enough that it needs to be watered, you still want the sensor to read this level as dry. So turning counterclockwise reduces the threshold to a level just above the current moisture level of the soil, which triggers the DO-LED to turn off.</p>
</li>
</ol>
<h3 id="heading-arduino-code-1">Arduino Code</h3>
<p>Upload the following sketch to the Arduino:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sensorPower = <span class="hljs-number">7</span>; <span class="hljs-comment">// Digital pin to power the sensor</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> sensorPin = <span class="hljs-number">2</span>; <span class="hljs-comment">// Digital input from the sensor</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> greenLED = <span class="hljs-number">13</span>; <span class="hljs-comment">// Green LED pin</span>
<span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> redLED = <span class="hljs-number">12</span>; <span class="hljs-comment">// Red LED pin</span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getSensorReading</span><span class="hljs-params">(<span class="hljs-keyword">int</span> digitalPin, <span class="hljs-keyword">int</span> powerPin)</span> </span>{  
  digitalWrite(powerPin, HIGH); <span class="hljs-comment">// Power ON sensor</span>
  delay(<span class="hljs-number">500</span>); <span class="hljs-comment">// Wait for sensor to stabilize</span>

  <span class="hljs-keyword">int</span> reading = digitalRead(digitalPin);

  digitalWrite(powerPin, LOW); <span class="hljs-comment">// Power OFF sensor</span>
  <span class="hljs-keyword">return</span> reading;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);

  pinMode(sensorPower, OUTPUT);
  pinMode(sensorPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

 <span class="hljs-comment">// Ensure everything starts OFF</span>
  digitalWrite(sensorPower, LOW);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">int</span> sensorReading = getSensorReading(sensorPin, sensorPower);

  Serial.println(<span class="hljs-string">"==================================="</span>);
  Serial.print(<span class="hljs-string">"Digital Reading: "</span>);
  Serial.println(sensorReading);

  <span class="hljs-keyword">if</span> (sensorReading == HIGH) {
    Serial.println(<span class="hljs-string">"Status: Soil moisture is LOW (dry)"</span>);
    Serial.println(<span class="hljs-string">"Action: Water the soil"</span>);
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
 } <span class="hljs-keyword">else</span> {
    Serial.println(<span class="hljs-string">"Status: Soil moisture is GOOD (wet)"</span>);
    Serial.println(<span class="hljs-string">"Action: No watering needed"</span>);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
 }

  Serial.println(<span class="hljs-string">"==================================="</span>);
  Serial.println(); 
  delay(<span class="hljs-number">2000</span>); <span class="hljs-comment">// Update every 2 seconds</span>
}
</code></pre>
<p>In the sketch, you define the digital pin used to read data from the sensor, the digital pins to power the sensor, and the green and red LEDs.</p>
<p>The <code>getSensorReading</code> function powers on the sensor, takes the digital reading from the sensor, powers off the sensor, and returns the digital reading taken from the sensor.</p>
<p>The <code>setup</code> function is routine: you set the baud rate, define the digital pins as input or output, and write a <code>LOW</code> to the output pins to ensure they are off at the start.</p>
<p>In the <code>loop</code> function, you call the <code>getSensorReading</code> to get the digital reading from the sensor. If the sensor outputs a <code>HIGH</code>, you turn on the red LED and print a message that the soil is dry. If the sensor outputs a <code>LOW</code>, you turn on the green LED and print a message that the soil is wet.</p>
<h3 id="heading-test-the-system-1">Test the System</h3>
<p>You can proceed to test the project using different moisture levels. For example:</p>
<ul>
<li>For wet soil, that is, if the moisture level is above the threshold, you should have the following output:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751910035826/19edc7e0-09a2-404a-8ce4-fb978c5b9f6b.jpeg" alt="Test example 2 with wet soil" width="2293" height="724" loading="lazy"></p>
<ul>
<li>For dry soil, that is, if the moisture level is below the threshold, you should have the following output:</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751910068607/33881bb3-ba7b-41fd-a637-001016298312.jpeg" alt="Test example 2 with dry soil" width="2293" height="724" loading="lazy"></p>
<p>You can also simulate the example on Tinkercad here: <a target="_blank" href="https://www.tinkercad.com/embed/2wHwfKherNz">https://www.tinkercad.com/embed/2wHwfKherNz</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752100906816/cd1b3de4-f5e6-4760-ab03-8f46443ba270.png" alt="Example 2 Tinkercad simulation" class="image--center mx-auto" width="1366" height="611" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned what a resistive soil moisture sensor is, how to calibrate the sensor for your soil type, and how to use the sensor's analog and digital data to determine the moisture level of the soil.</p>
<p>The examples provided a solid foundation for working with the sensor. You can extend these examples into more complex projects, such as an automated irrigation system or remote monitoring of soil moisture.</p>
<p>For projects that require greater accuracy and frequent or sustained sensor operation, you should explore the capacitive sensor.</p>
<p>You can access all the code on <a target="_blank" href="https://github.com/michaelikoko/resistive-soil-moisture-sensor">GitHub</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Arduino in Spanish - Course for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Arduino is an open-source electronics platform that allows you to control the physical world through programming. With Arduino, you can read sensor data, control motors, light LEDs, and much more. It's a great way to learn electronics and programming... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-arduino-in-spanish-course-for-beginners/</link>
                <guid isPermaLink="false">675194a23929bef2d9561a44</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Estefania Cassingena Navone ]]>
                </dc:creator>
                <pubDate>Thu, 05 Dec 2024 11:55:14 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733088215802/7caee798-7552-4b20-ab4f-41cab4cd24c8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Arduino is an open-source electronics platform that allows you to control the physical world through programming. With Arduino, you can read sensor data, control motors, light LEDs, and much more. It's a great way to learn electronics and programming.</p>
<p>We just published a course on the <a target="_blank" href="https://www.youtube.com/freecodecampespanol">freeCodeCamp.org Spanish YouTube channel</a> that will teach you the fundamentals of Arduino step by step. You'll learn key programming concepts, like data types, variables, functions, operators, conditionals, and loops, alongside concepts related to electronics, such as digital input and output, time, buttons, temperature and humidity, movement sensors, and more.</p>
<p>If you have Spanish-speaking friends, you are welcome to share the <a target="_blank" href="https://www.freecodecamp.org/espanol/news/curso-de-arduino-desde-cero/"><strong>Spanish version of this article</strong></a> with them.</p>
<p>The course was created by Carlos Leon. Carlos is a developer who is passionate about Arduino and who loves sharing his knowledge of programming and electronics with everyone who is interested in learning these technologies.</p>
<h2 id="heading-what-is-arduino">What is Arduino?</h2>
<p>Arduino is an open-source electronics platform that connects the digital and physical worlds. It consists of a microcontroller board and a user-friendly development environment. By connecting various sensors, actuators, and other electronic components to the Arduino board, you can create interactive projects that respond to the real world.</p>
<p>With Arduino, you can build a wide range of projects, from simple circuits to complex robotics systems. You can also practice your problem-solving skills and gain a deeper understanding of programming fundamentals and electronics.</p>
<p>This course is great for anyone who is interested in learning more about Arduino. It’s a stepping stone into the world of robotics, automation, Internet of Things, and wearable technology.</p>
<p>💡 <strong>Tip:</strong> During the course, you’ll use an Arduino simulator, so you can take the course even if you don’t have an Arduino board available.</p>
<h2 id="heading-arduino-course">Arduino Course</h2>
<p>Great! Now that you know more about Arduino, let’s check out some of the topics that you’ll learn during the course:</p>
<ul>
<li><p>Introduction</p>
</li>
<li><p>Arduino Uno</p>
</li>
<li><p>Pins</p>
</li>
<li><p>Electricity concepts</p>
</li>
<li><p>Calculating resistance</p>
</li>
<li><p>Breadboard</p>
</li>
<li><p>Programming fundamentals</p>
</li>
<li><p>About Wokwi</p>
</li>
<li><p>Data types</p>
</li>
<li><p>Variables</p>
</li>
<li><p>Functions</p>
</li>
<li><p>Operators</p>
</li>
<li><p>Conditionals</p>
</li>
<li><p>Loops</p>
</li>
<li><p>Serial console</p>
</li>
<li><p>Hello World with Arduino</p>
</li>
<li><p>Pin declarations</p>
</li>
<li><p>Digital input-output</p>
</li>
<li><p>Analog input-output</p>
</li>
<li><p>Time</p>
</li>
<li><p>Buttons</p>
</li>
<li><p>Libraries</p>
</li>
<li><p>Sensors</p>
</li>
<li><p>Temperature and Humidity</p>
</li>
<li><p>Ultrasonic</p>
</li>
<li><p>Movement sensor</p>
</li>
<li><p>Interesting components</p>
</li>
<li><p>LCD screen</p>
</li>
<li><p>Servomotors</p>
</li>
<li><p>And more…</p>
</li>
</ul>
<p>Check out these course screenshots:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733089419786/cb54cc7c-15aa-446a-8fdd-5ec2fdec542b.png" alt="A course slide, showing an Arduino board and two images related to electronics." class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733089335855/6e032dae-6fc2-46b6-aa9d-e661cf9b6c3c.png" alt="A course slide, showing analog input and output in an Arduino simulator." class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1733089362587/b8bf731a-ff26-4c93-8f6f-6699ca202a7b.png" alt="A course screenshot, showing an Arduino simulator with code on the left and the board on the right." class="image--center mx-auto" width="1920" height="1080" loading="lazy"></p>
<p>💡 <strong>Tip:</strong> The course is beginner-friendly. It’s great for you if you’re just getting started in the world of programming and electronics. You’ll even write your first “Hello, world!” program in Arduino.</p>
<p>If you’re ready to start learning, check out the course in Spanish on the <a target="_blank" href="https://www.youtube.com/freecodecampespanol">freeCodeCamp.org Spanish YouTube channel</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/JOLB4I1nEus" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>✍️ Course created by Carlos Leon.</p>
<ul>
<li>LinkedIn: <a target="_blank" href="http://www.linkedin.com/in/leoncarlo/">Carlos Leon</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Switch Case in Arduino – Control LEDs With the Switch Statement ]]>
                </title>
                <description>
                    <![CDATA[ You can use a switch case statement to execute different blocks of code based on the value of a variable. It offers a more direct and cleaner approach to handling multiple conditions. In this article, you'll learn how to control LEDs using a switch c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-switch-case-in-arduino-control-leds/</link>
                <guid isPermaLink="false">670544332dc3e880b06ac749</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 08 Oct 2024 14:39:47 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728178146204/a1c1a6af-b4ce-4fe4-a73d-8861d63cc01e.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use a <code>switch case</code> statement to execute different blocks of code based on the value of a variable. It offers a more direct and cleaner approach to handling multiple conditions.</p>
<p>In this article, you'll learn how to control LEDs using a <code>switch case</code> statement in Arduino. You can also find the <code>switch case</code> statement in other programming languages, so this can serve as a practical example of how they work.</p>
<p>Here’s a demo of what you’ll be building:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728301474557/f67ddfe7-0cf1-47ee-9732-90f3a4b1649c.gif" alt="f67ddfe7-0cf1-47ee-9732-90f3a4b1649c" class="image--center mx-auto" width="298" height="168" loading="lazy"></p>
<p>You can watch the video version of this article here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/TAU_osZ6aGQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-hardware-components"><strong>Hardware Components</strong></h2>
<p>Here are the components you'll need to follow along:</p>
<ul>
<li><p>Arduino board (Uno).</p>
</li>
<li><p>Potentiometer.</p>
</li>
<li><p>Breadboard.</p>
</li>
<li><p>Three LEDs.</p>
</li>
<li><p>Resistors for the LEDs.</p>
</li>
<li><p>Jumper wires.</p>
</li>
</ul>
<h2 id="heading-how-to-use-a-switch-case-statement-in-arduino"><strong>How to Use a</strong> <code>Switch Case</code> Statement in Arduino</h2>
<p>Here's the syntax/structure of a <code>switch</code> statement:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">switch</span> (variable) {
  <span class="hljs-keyword">case</span> value1:
    <span class="hljs-comment">// code to be executed if variable == value1</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> value2:
    <span class="hljs-comment">// code to be executed if variable == value2</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-comment">// code to be executed if variable doesn't match any case</span>
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>Let's break it down:</p>
<ul>
<li><p><code>variable</code>: This denotes the variable being evaluated. The value of the variable determines how the code blocks will be executed.</p>
</li>
<li><p><code>case</code>: Each <code>case</code> represents a value that may match the variable being evaluated. If the <code>variable</code> and a <code>case</code> have the same value, the code for that case will be executed. You can have as many cases as you want.</p>
</li>
<li><p><code>break</code>: After a code block in a <code>case</code> has been executed, the <code>break</code> keyword terminates the code. That is, it stops the code from moving on to other cases because a match has already been found.</p>
</li>
<li><p><code>default</code>: In a situation where none of the cases match the <code>variable</code>, the code in the <code>default</code> block will be executed.</p>
</li>
</ul>
<p>Next, let's use a <code>switch</code> statement to control LEDs.</p>
<h3 id="heading-switch-case-in-arduino-example"><code>Switch Case</code> in Arduino Example</h3>
<h4 id="heading-circuit-diagram"><strong>Circuit Diagram</strong></h4>
<p>Here’s how to connect your components:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728177876221/e58910e9-f8be-430b-a220-cda2cc9b956a.png" alt="Circuit diagram showing potentiometer and LEDs connected to an Arduino Uno R3 board" class="image--center mx-auto" width="1920" height="814" loading="lazy"></p>
<p>The goal here is to decide which LED (or a combination of LEDs) comes on based on the value of a variable.</p>
<h4 id="heading-potentiometer-connection"><strong>Potentiometer Connection</strong></h4>
<ul>
<li><p>Connect the left terminal of the potentiometer to 5V.</p>
</li>
<li><p>Connect the right terminal to GND.</p>
</li>
<li><p>Connect the middle terminal to A0.</p>
</li>
</ul>
<h4 id="heading-led-connection"><strong>LED Connection</strong></h4>
<ul>
<li><p>For each LED, connect the shorter leg to GND.</p>
</li>
<li><p>Connect each longer leg to a digital pin. I recommend using pin 8 (for the green LED), 9 (for the yellow LED), and 10 (for the red LED) to match what we have in the circuit diagram. We'll also use these values in the code.</p>
</li>
</ul>
<p>Here's the full project code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> greenLED = <span class="hljs-number">8</span>;
<span class="hljs-keyword">int</span> yellowLED = <span class="hljs-number">9</span>;
<span class="hljs-keyword">int</span> redLED = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> potPin = A0; 
<span class="hljs-keyword">int</span> potValue;
<span class="hljs-keyword">int</span> mappedPotValue;
​
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  Serial.begin(<span class="hljs-number">9600</span>);
}
​
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  potValue = analogRead(potPin);
  mappedPotValue = <span class="hljs-built_in">map</span>(potValue, <span class="hljs-number">0</span>, <span class="hljs-number">1023</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>);
​
  <span class="hljs-keyword">switch</span> (mappedPotValue) {
    <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
      digitalWrite(greenLED, HIGH);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, HIGH);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, HIGH);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">4</span>:
      digitalWrite(greenLED, HIGH);
      digitalWrite(yellowLED, HIGH);
      digitalWrite(redLED, HIGH);
      Serial.println(mappedPotValue);
      delay(<span class="hljs-number">500</span>);
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      delay(<span class="hljs-number">500</span>);
      <span class="hljs-keyword">break</span>;
  }
}
</code></pre>
<p>Let's break down the code.</p>
<h4 id="heading-variable-initialization"><strong>Variable Initialization</strong></h4>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> greenLED = <span class="hljs-number">8</span>;
<span class="hljs-keyword">int</span> yellowLED = <span class="hljs-number">9</span>;
<span class="hljs-keyword">int</span> redLED = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> potPin = A0; 
<span class="hljs-keyword">int</span> potValue;
<span class="hljs-keyword">int</span> mappedPotValue;
</code></pre>
<p>We started by initializing variables to correspond with the hardware connections.</p>
<p><code>greenLED</code>, <code>yellowLED</code>, and <code>redLED</code> have values of 8, 9, and 10, respectively. This matches the pins they were connected to on the Arduino board. Similarly, <code>potPin</code>, which is the variable for the potentiometer, has a value of A0.</p>
<p>You'll use the <code>potValue</code> variable to store the current value of the potentiometer. We also created a <code>mappedPotValue</code> variable to store the range of values needed for the LEDs in a minute.</p>
<h4 id="heading-pinmode-and-serial-monitor"><strong>pinMode and Serial Monitor</strong></h4>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  Serial.begin(<span class="hljs-number">9600</span>);
}
</code></pre>
<p>In the <code>setup()</code> function, we set the LEDs as output pins and initialized the serial monitor.</p>
<h4 id="heading-logic-for-switch-case-statement"><strong>Logic for</strong> <code>switch case</code> Statement</h4>
<p>First, we read the value of the potentiometer using the <code>analogRead()</code> function and stored it in the <code>potValue</code> variable:</p>
<pre><code class="lang-cpp">potValue = analogRead(potPin);
</code></pre>
<p>We then converted the values from the potentiometer to a range of 0 to 4 using the <code>map</code> function and stored them in the <code>mappedPotValue</code> variable:</p>
<pre><code class="lang-cpp">mappedPotValue = <span class="hljs-built_in">map</span>(potValue, <span class="hljs-number">0</span>, <span class="hljs-number">1023</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>);
</code></pre>
<p>Next, we created a <code>switch</code> statement—the value being evaluated is <code>mappedPotValue</code>. Recall that this is the variable where we stored the potentiometer values. So whenever you turn the potentiometer, the value changes and potentially matches a <code>case</code>:</p>
<pre><code class="lang-cpp">  <span class="hljs-keyword">switch</span> (mappedPotValue) {
    <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
      digitalWrite(greenLED, HIGH);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, HIGH);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, HIGH);
      Serial.println(mappedPotValue);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">4</span>:
      digitalWrite(greenLED, HIGH);
      digitalWrite(yellowLED, HIGH);
      digitalWrite(redLED, HIGH);
      Serial.println(mappedPotValue);
      delay(<span class="hljs-number">500</span>);
      digitalWrite(greenLED, LOW);
      digitalWrite(yellowLED, LOW);
      digitalWrite(redLED, LOW);
      Serial.println(mappedPotValue);
      delay(<span class="hljs-number">500</span>);
      <span class="hljs-keyword">break</span>;
  }
</code></pre>
<p>We passed <code>mappedPotValue</code> as a parameter to <code>switch</code> since it's the variable being compared to different cases: <code>switch (mappedPotValue)</code>.</p>
<ul>
<li><p>For <code>case 0</code>, all the LEDs will be off.</p>
</li>
<li><p>For <code>case 1</code>, only the green LED comes on.</p>
</li>
<li><p>For <code>case 2</code>, only the yellow LED comes on.</p>
</li>
<li><p>For <code>case 3</code>, only the red LED comes on.</p>
</li>
<li><p>For <code>case 4</code>, all three LEDs will blink continuously.</p>
</li>
</ul>
<p>Using a <code>switch</code> statement, you've successfully controlled the behavior of LEDs based on the value of a potentiometer!</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, you learned how to use a <code>switch case</code> statement in Arduino using a practical example.</p>
<p>You learned how to control different LEDs based on the value of a potentiometer. You achieved this by using different cases in a <code>switch</code> statement to match the potentiometer's current value and execute the corresponding code.</p>
<p><code>switch</code> statements can be used in different ways to make a project more dynamic. Some use cases in Arduino include:</p>
<ul>
<li><p>Managing and interpreting the different values, modes, and states of a component or sensor.</p>
</li>
<li><p>Performing actions based on specific commands. For example, rotating a robotic arm to a specific angle/direction.</p>
</li>
<li><p>Mapping button presses to user input, and so on.</p>
</li>
</ul>
<p>You can watch the video version of this project <a target="_blank" href="https://www.youtube.com/watch?v=TAU_osZ6aGQ">here</a>. The full project code is available on <a target="_blank" href="https://github.com/ihechikara/switch-case-arduino">GitHub</a>.</p>
<p>Check out <a target="_blank" href="https://ihechikara.com/">my blog</a> for articles about embedded systems, IoT, and web development.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Control the Brightness of an LED with a Potentiometer ]]>
                </title>
                <description>
                    <![CDATA[ Potentiometers are used in various electronic circuits and systems. You can use them in electronic devices to control volume, brightness, motor speed, voltage regulation, and so on. You've most likely used a potentiometer before with appliances like ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/control-led-with-potentiometer/</link>
                <guid isPermaLink="false">66b0a2863dc92ea6a5a091d9</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 18 Mar 2024 19:48:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/cover-image-potentiometer.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Potentiometers are used in various electronic circuits and systems. You can use them in electronic devices to control volume, brightness, motor speed, voltage regulation, and so on.</p>
<p>You've most likely used a potentiometer before with appliances like radios, microwaves, blenders, electric fans, game controllers, and others.</p>
<p>They are generally used to provide or control different ranges of variable resistance in electronic circuits.</p>
<p>In this article, you'll learn the following:</p>
<ul>
<li>How to connect a potentiometer to an Arduino board.</li>
<li>How to get the values of a potentiometer.</li>
<li>How to control the brightness of an LED using a potentiometer.</li>
</ul>
<p>You can also watch the video version of this article here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/dwZCgzlYfoA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-hardware-components">Hardware Components</h2>
<p>Here are the hardware components you'll need to follow along:</p>
<ul>
<li>Arduino board.</li>
<li>Potentiometer.</li>
<li>Breadboard.</li>
<li>LED.</li>
<li>1K Ohm resistor.</li>
<li>Jumper wires.</li>
</ul>
<h2 id="heading-how-to-connect-a-potentiometer-to-an-arduino-board">How to Connect a Potentiometer to an Arduino Board</h2>
<p>The potentiometer is made up of three terminals: two outer terminals and the middle terminal. Either of the outer terminals can be connected to either 5V or GND (ground). That is:</p>
<ul>
<li>If you connect the left outer terminal to 5V, you have to connect the right outer terminal to GND.</li>
<li>If you connect the left outer terminal to GND, you have to connect the right outer terminal to 5V.</li>
</ul>
<p>The middle terminal serves as the output terminal. We'll connect it to an analog pin. You can read the varying values of the potentiometer from the output terminal.</p>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/circuit-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>circuit diagram</em></p>
<p>Here's how the potentiometer was connected in the diagram above:</p>
<ul>
<li>The left outer terminal of the potentiometer was connected to GND.</li>
<li>The right outer terminal was connected to  5V.</li>
<li>The middle terminal (output terminal) was connected to analog pin A0 on the Uno board.</li>
</ul>
<p>Here's how the LED was connected:</p>
<ul>
<li>The shorter leg of the LED was connected to GND.</li>
<li>The longer leg was connected to digital pin 6 through a 1K Ohm resistor.</li>
</ul>
<p>Make sure to connect the LED to a digital pin with the ~ symbol. Such pins support pulse width modulation, which lets you send analog signals to digital pins.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> potPin = A0;
<span class="hljs-keyword">int</span> potValue = <span class="hljs-number">0</span>;
<span class="hljs-keyword">int</span> brightness = <span class="hljs-number">0</span>;
<span class="hljs-keyword">int</span> ledPin = <span class="hljs-number">6</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  pinMode(ledPin, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  potValue = analogRead(potPin);
  brightness = (<span class="hljs-number">255.0</span>/<span class="hljs-number">1023.0</span>)*potValue;
  analogWrite(ledPin, brightness);
}
</code></pre>
<p>Let's break down the code.</p>
<h3 id="heading-initialize-variables">Initialize Variables</h3>
<p>We started by initializing our variables:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> potPin = A0;
<span class="hljs-keyword">int</span> potValue = <span class="hljs-number">0</span>;
<span class="hljs-keyword">int</span> brightness = <span class="hljs-number">0</span>;
<span class="hljs-keyword">int</span> ledPin = <span class="hljs-number">6</span>;
</code></pre>
<p>The <code>potPin</code> variable has a value of A0. This represents the A0 pin connected to the output pin of the potentiometer.</p>
<p>We then declared a <code>potValue</code> variable, which will be used to store the values from <code>potPin</code>.</p>
<p>The <code>brightness</code> variable will be used to control the brightness of the LED.</p>
<p>The LED pin was connected to digital pin 6 on the Uno board, so we initialized a <code>ledPin</code> variable with a value of 6: <code>int ledPin = 6;</code>.</p>
<h3 id="heading-serial-monitor-and-pinmode">Serial Monitor and pinMode</h3>
<p>Next, in the <code>loop()</code> function, we initialized the serial monitor and set the LED pin to serve as an output pin:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  pinMode(ledPin, OUTPUT);
}
</code></pre>
<h3 id="heading-create-logic-to-control-led-brightness">Create Logic to Control LED Brightness</h3>
<p>In the <code>loop()</code> function, we have three lines of code:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  potValue = analogRead(potPin);
  brightness = (<span class="hljs-number">255.0</span>/<span class="hljs-number">1023.0</span>)*potValue;
  analogWrite(ledPin, brightness);
}
</code></pre>
<p>In the first line, we used the <code>analogRead()</code> function to read the value of <code>potPin</code>. The read values were assigned to the <code>potValue</code> variable.</p>
<p>At this point, if you print <code>potValue</code> to the serial monitor using <code>Serial.println(potValue);</code>, you'll get a range of values from 0 to 1023 when you tune the knob of the potentiometer.</p>
<p>For the <code>brightness</code> variable, we converted the values from the potentiometer to fall with the range of 0 to 255: <code>brightness = (255.0/1023.0)*potValue;</code>. This is because the <code>analogWrite()</code> function only accepts values within that range, and not the default 0 to 1023 that the potentiometer produces.</p>
<p>Lastly, we used the <code>analogWrite()</code> function to send values to the LED: <code>analogWrite(ledPin, brightness);</code>.</p>
<p>The <code>analogWrite()</code> function's first parameter is the <code>ledPin</code>, which denotes the pin where the values should be sent. The second parameter is <code>brightness</code>, which denotes a range of values to be sent to the LED (<code>ledPin</code>).</p>
<p>When you upload the code to your board, the LED should have varying levels of brightness as you tune the potentiometer.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to control the brightness on an LED using a potentiometer. You also saw how to connect the components to digital and analog pins on an Arduino board.</p>
<p>Finally, you learned about how to make the components work together using code.</p>
<p>You can find the code for this project <a target="_blank" href="https://github.com/ihechikara/control-led-with-potentiometer/blob/main/pot.ino">here</a>. You can watch the video version <a target="_blank" href="https://youtu.be/dwZCgzlYfoA?si=k9W9eAEjcc4yLxqe">here</a>.</p>
<p>Check out <a target="_blank" href="https://ihechikara.com/">my blog</a> for articles about embedded systems, IoT, and web development.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Arduino for Everybody ]]>
                </title>
                <description>
                    <![CDATA[ Arduino is an open-source electronics platform that allows you to create interactive devices with sensors and outputs. With Arduino, you can build DIY electronics projects with minimal technical knowledge. We just published a comprehensive Arduino co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/arduino-for-everybody/</link>
                <guid isPermaLink="false">66b2008fa8b92c93292363ff</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Wed, 08 Nov 2023 15:12:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/arduino.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Arduino is an open-source electronics platform that allows you to create interactive devices with sensors and outputs. With Arduino, you can build DIY electronics projects with minimal technical knowledge.</p>
<p>We just published a comprehensive Arduino course on the freeCodeCamp.org YouTube channel. The course covers the basics of Arduino, from hardware components to software programming. It also includes a series of hands-on projects that you can build to apply your knowledge.</p>
<p>Arduino is easy to use even for hobbyists and beginners with little to no experience in electronics. Mathewos Wondwosen created this course. He has a lot of experience creating with Arduino and he is a great person to teach this course.</p>
<p>Here are a few types of projects that people sometimes use Arduino for.</p>
<ul>
<li><strong>Controlling LEDs:</strong> Arduino can be used to control LEDs to create different patterns and animations.</li>
<li><strong>Creating interactive projects:</strong> Arduino can be used to create interactive projects, such as game controllers, robots, and home automation devices.</li>
<li><strong>Measuring and collecting data:</strong> Arduino can be used to measure and collect data from sensors, such as temperature, humidity, and light.</li>
<li><strong>Controlling motors:</strong> Arduino can be used to control motors, such as servo motors and stepper motors.</li>
</ul>
<p>Throughout the course, you will build 14 hands-on Arduino projects while learning:</p>
<ul>
<li>How to set up the Arduino IDE</li>
<li>Basic electronics components like resistors, LEDs, and buttons</li>
<li>Essential coding concepts like variables and loops</li>
<li>How to connect sensors, displays, and more</li>
</ul>
<p>By the end of the course, you will have the skills to create your own interactive Arduino prototypes using lights, buzzers, displays, sensors, and more.</p>
<p>Here are all the sections in this course:</p>
<ul>
<li>Introduction to Arduino</li>
<li>Buying the right Arduino Kit</li>
<li>Using a Digital Simulator</li>
<li>Project #1 Overview: Basic LED Circuit</li>
<li>Breadboards</li>
<li>Resistors</li>
<li>LEDs</li>
<li>Assembly</li>
<li>Project Recap</li>
<li>Arduino Installation</li>
<li>Project #2: LED Blink Project</li>
<li>Homework #1</li>
<li>Project #3: LED Traffic Light</li>
<li>Variables</li>
<li>Project Recap</li>
<li>Project #4: Analog Pins</li>
<li>Project #5: Volt Reader</li>
<li>Project #6: Dimmable LED with Potentiometer</li>
<li>Project # 7: Simple Buzz Modulator</li>
<li>Project #8: Melody Buzzer</li>
<li>Photoresistor</li>
<li>Thermistor</li>
<li>Temperature Sensor</li>
<li>Project #9: LM Temperature Sensor</li>
<li>Project #9: DHT Sensor</li>
<li>Project #10: Pushbuttons &amp; Switches</li>
<li>RGB LED</li>
<li>Project #11: Color Picker RGB LED</li>
<li>One Digit 7-Segment LED Display</li>
<li>Project #12: Countdown timer</li>
<li>Four Digit 7-Segment LED Display</li>
<li>Project #13: Alarm Timer</li>
<li>X 8 LED Matrix</li>
<li>Project #14: Input Display</li>
</ul>
<p>Watch the full course on the <a target="_blank" href="https://www.youtube.com/watch?v=DPqiIzK97K0">freeCodeCamp.org YouTube channel</a> (10-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/DPqiIzK97K0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Arduino Handbook – Learn Microcontrollers for Embedded Systems ]]>
                </title>
                <description>
                    <![CDATA[ Arduino is an open-source platform that combines hardware and software in designing and building electronic projects. Arduino can be applied in a variety of projects like: Home automation. Internet of Things (IoT). Audio and music. Automated and rem... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-arduino-handbook/</link>
                <guid isPermaLink="false">66b0a3683ac4671a1e580305</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 05 Oct 2023 13:15:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/The-Arduino-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Arduino is an open-source platform that combines hardware and software in designing and building electronic projects.</p>
<p>Arduino can be applied in a variety of projects like:</p>
<ul>
<li>Home automation.</li>
<li>Internet of Things (IoT).</li>
<li>Audio and music.</li>
<li>Automated and remote controlled systems.</li>
<li>Automation in agriculture.</li>
<li>Electronic prototyping.</li>
<li>Wearable devices, and so much more.</li>
</ul>
<p>The hardware part of Arduino comprises Arduino boards, input and output devices (including digital and analog pins, and sensors and actuators), shields, breadboards, jumper wires, and so on. These components can be combined together to create dynamic and interactive projects. </p>
<p>The software is made up of the development tools used to write, debug, compile, and upload code to Arduino boards. Most 0f the software tools can be found in the Arduino IDE (Integrated Development Environment).</p>
<p>This handbook will help you understand how Arduino works. You'll learn about the Arduino boards, the components that make up a board, and how to connect devices to them.</p>
<p>We'll talk about input and output peripherals which help the microcontroller (the brain of the Arduino board) process information coming from the physical environment, and send output based on programmed logic. </p>
<p>You'll learn about the Arduino IDE, how to code using the Arduino programming language, and how to use sensors, actuators, and other components to build projects as you learn. </p>
<p>You'll also learn about serial communication, which helps Arduino boards communicate with other computers.</p>
<p>This handbook is written for makers (students, artists, hobbyists, programmers) who are beginners.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Although it would be helpful, you don't need prior programming knowledge to use this handbook. You will learn the basics of Arduino programming from scratch. This can also serve as your introduction to programming.</p>
<p>To make it beginner friendly, we won't talk about some aspects of electronics like current and voltage, resistance, circuits (series and parallel), and most basic electronic/electrical laws and requirements for students in STEM (Science, Technology, Engineering, Mathematics) fields.</p>
<p>Whether you have knowledge of these concepts or not, you can learn about Arduino using this handbook.</p>
<p>If you know how to use a breadboard and a resistor, then that's all the knowledge on electronics you'll need to follow along. </p>
<p>In summary, this handbook is for everyone. You don't need an engineering degree to become an Arduino maker!</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-chapter-1-getting-started-with-arduino">Chapter 1: Getting Started with Arduino</a></li>
<li><a class="post-section-overview" href="#heading-chapter-2-basics-of-arduino-programming">Chapter 2: Basics of Arduino Programming</a></li>
<li><a class="post-section-overview" href="#heading-chapter-3-how-to-use-digital-pins-in-arduino">Chapter 3: How to use Digital Pins in Arduino</a></li>
<li><a class="post-section-overview" href="#heading-chapter-4-how-to-use-analog-pins-in-arduino">Chapter 4: How to use Analog Pins in Arduino</a></li>
<li><a class="post-section-overview" href="#heading-chapter-5-how-to-use-sensors-and-actuators-in-arduino">Chapter 5: How to use Sensors and Actuators in Arduino</a></li>
<li><a class="post-section-overview" href="#heading-chapter-6-how-to-use-the-serial-monitor-in-arduino-2">Chapter 6: How to use the Serial Monitor in Arduino</a></li>
<li><a class="post-section-overview" href="#heading-chapter-7-how-to-use-displays-in-arduino">Chapter 7: How to use Displays in Arduino</a></li>
</ul>
<h1 id="heading-chapter-1-getting-started-with-arduino">Chapter 1: Getting Started with Arduino</h1>
<p>The Arduino development and design process comprises both hardware and software. So knowing how they work together is important for building the right foundation for your journey.</p>
<p>In this chapter, you’ll learn about the different components that make up the Arduino Uno board. You'll also learn how to install the Arduino IDE and set up your development environment.</p>
<p>At the time of writing, a new Uno board was released — the Arduino Uno R4. This handbook will make use of the Uno R3 board, but you can follow along with either of them. The R4 board comes in two variants — Arduino Uno R4 WiFi and Arduino Uno R4 Minima — with cool additional features that you can read about <a target="_blank" href="https://blog.arduino.cc/2023/06/26/uno-r4-the-new-dimension-of-making/?_gl=1*18ccx2k*_ga*MTkzMTc3MDUxNC4xNjc5NjU4Mzkz*_ga_NEXN8H46L5*MTY4Nzk0Njg3Mi40LjEuMTY4Nzk0ODE3MS4wLjAuMA..">here</a>.</p>
<h2 id="heading-components-of-the-arduino-uno-r3-board">Components of the Arduino Uno R3 Board</h2>
<p>There are many types of Arduino boards like Arduino Nano, Arduino Uno, Arduino Mega, Arduino Leonardo, and so on.</p>
<p>These boards have some common features — they all have digital and output pins, they’re programmable, and they all have a microcontroller.</p>
<p>But there are also some differences. Each board varies in size and shape, and usually has more or fewer components when compared to other boards.</p>
<p>The common boards you’ll come across as a beginner are the Nano, Uno, and Mega boards. The most commonly used is the Uno board, which we’ll use for this handbook.</p>
<p>Here are some of the components you'll find on the Uno R3 board:</p>
<ul>
<li>A power port.</li>
<li>USB connector.</li>
<li>Microcontroller (ATmega328).</li>
<li>Analog pins.</li>
<li>Digital pins.</li>
<li>Reset button.</li>
<li>TX and RX indicators.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/UnoR3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Arduino Uno R3 board (https://store.arduino.cc/products/arduino-uno-rev3)</em></p>
<p>You’ll make use of most of the components listed above as you progress through this handbook.</p>
<h2 id="heading-how-to-install-and-set-up-the-arduino-ide">How to Install and Set Up the Arduino IDE</h2>
<p>You can use the Arduino IDE to program Arduino boards. That is, you write the code in the IDE, then upload it to the board.</p>
<p>In this section, you’ll learn how to set up the IDE, and create your first Arduino program (also called an Arduino sketch).</p>
<p>You can download the latest version of the Arduino IDE on the <a target="_blank" href="https://www.arduino.cc/en/software">Arduino software download page</a>. You can download the IDE for different operating systems — Windows, MacOS, and Linux.</p>
<p>The installation process is similar for the operating systems listed above. Here’s how to install it on a Windows machine:</p>
<h3 id="heading-step-1-download-the-arduino-ide">Step #1 – Download the Arduino IDE</h3>
<p>The first step is to download the IDE from the <a target="_blank" href="https://www.arduino.cc/en/software">Arduino software download page</a>. You should see a section of the page similar to the image below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/arduino-download-page-options.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On the right side of the image above are different download options for specific operating systems. Make sure you download the option that suits your operating system.</p>
<p>I'll use the ZIP file option for Windows. If you decide to download an installer instead, then you can follow the installation steps after clicking the installation file.</p>
<h3 id="heading-step-2-unzip-the-downloaded-file">Step #2 – Unzip the Downloaded File</h3>
<p>Go on and unzip the downloaded file. This gives you access to all the resources needed to run the Arduino IDE.</p>
<p>After unzipping the file, you should see files like these:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/arduino-ide-unzipped.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Image showing the files you should see</em></p>
<p>To launch the Arduino IDE, click on the file that says “Arduino IDE”.</p>
<h3 id="heading-step-3-overview-of-the-arduino-ide">Step #3 – Overview of the Arduino IDE</h3>
<p>Now that you’ve downloaded and installed the Arduino IDE, the next part is to get familiar with the development environment. In the next section, you’ll learn how to upload code to an Arduino Uno board using the IDE.</p>
<p>Before that, let’s have a look at some options you’ll find in the Arduino IDE. At the top left corner of the IDE are five options — File, Edit, Sketch, Tools, Help:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/ide.png" alt="Image" width="600" height="400" loading="lazy">
<em>Screenshot showing these options (File, Edit, Sketch, Tools, Help)</em></p>
<p>The “File” option lets you do different things like creating a new sketch (we’ll talk about sketches in the next section), opening an existing sketch, Arduino practice examples for beginners, keyboard shortcuts, save options, and so on.</p>
<p>The “Edit” option gives you access to text formatting options like copy, paste, cut, comment/uncomment code, font size options, text search options, and so on.</p>
<p>You can use the “Sketch” option to verify and compile code, upload code to Arduino boards, optimize code, and add libraries.</p>
<p>You can use the “Tools” option to manage libraries, format code, access the serial monitor and plotter, select an Arduino board and port to upload code to, choose a processor, and so on.</p>
<p>The “Help” option provides resources for troubleshooting, information on IDE updates, guides on “getting started”, and so on.</p>
<p>Next, let’s look at some other parts and functionalities in the IDE that you’ll find useful. The image below, from the <a target="_blank" href="https://docs.arduino.cc/software/ide-v2/tutorials/getting-started-ide-v2">Arduino documentation</a>, highlights them perfectly:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/arduino-ide-icons.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://docs.arduino.cc/software/ide-v2/tutorials/getting-started-ide-v2">https://docs.arduino.cc/software/ide-v2/tutorials/getting-started-ide-v2</a></em></p>
<ul>
<li><strong>Verify/Upload</strong>: You can use these options to compile and upload code to Arduino boards. You’ll get error messages if the code doesn't compile as expected.</li>
<li><strong>Select Board &amp; Port</strong>: You can use this option to select a port and port number to upload your code too. The current version of the Arduino IDE automatically detects both boards and ports.</li>
<li><strong>Sketchbook</strong>: This gives you access to all the sketches created in your computer. You can also access sketches saved on Arduino Cloud (mostly used for creating IoT projects).</li>
<li><strong>Boards Manager</strong>: The Arduino IDE comes with support for different boards. As you progress through your journey, you’ll make use of different boards and some of them may not be supported by the IDE. The board manager tab lets you install and manage packages required to use these boards.</li>
<li><strong>Library Manager</strong>: You can use libraries to extend certain functionalities in code. Through the library manager, you can install numerous libraries that’ll help simplify the development process for you.</li>
<li><strong>Debugger</strong>: This is used for real time testing and debugging of Arduino programs.</li>
<li><strong>Search</strong>: You can use the search tool to find specific keywords in your code.</li>
<li><strong>Open Serial Monitor</strong>: You can use the serial monitor to communicate with Arduino boards, debug and test code, visualize data from your boards, interact with user input, and so on. We’ll look at the serial monitor in depth in a different chapter.</li>
<li><strong>Open Serial Plotter</strong>: The serial plotter is mostly used for real-time visualization of numerical data.</li>
</ul>
<h2 id="heading-what-is-an-arduino-sketch">What Is an Arduino Sketch?</h2>
<p>We mentioned the term “sketch” a couple of times in the last section, but what is it? A sketch is a program written with the Arduino programming language. It’s another way of referring to a code file written for Arduino projects.</p>
<p>The Arduino programming language is built upon the C/C++ language so they both share similar syntax and structure. You may come across resources that refer to Arduino code as “embedded C” or “embedded C++”.</p>
<h2 id="heading-how-to-upload-code-to-an-arduino-board">How to Upload Code to an Arduino Board</h2>
<p>To upload code to an Arduino board, you'll need both hardware and software. The hardware is the board which is the Uno board in our case, and the software is the Arduino sketch in the IDE.</p>
<p>Here are the steps:</p>
<h3 id="heading-step-1-connect-the-arduino-board">Step #1 – Connect the Arduino Board</h3>
<p>Connect the Arduino board to your computer using the USB cable. Without this step, you can't go further.</p>
<h3 id="heading-step-2-create-a-sketch">Step #2 – Create a Sketch</h3>
<p>Now it's time to launch the IDE and write some code. </p>
<p>Here's a code example that makes an LED blink:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> ledPin = <span class="hljs-number">13</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(ledPin, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  digitalWrite(ledPin, HIGH);
  delay(<span class="hljs-number">1000</span>);
  digitalWrite(ledPin, LOW);
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>Don't worry if you don't understand the code — we'll cover everything as we go further.</p>
<h3 id="heading-step-3-select-the-board-and-port">Step #3 – Select the Board and Port</h3>
<p>You can select the board to upload your code to from the IDE. Here's an image showing what that looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/port.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-step-4-verify-the-code">Step #4 – Verify the Code</h3>
<p>You can use the verify button to compile the code and check for errors. If errors exist, you'll get an error message to show you the possible cause.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/verify.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image showing the verify button</em></p>
<h3 id="heading-step-5-upload-the-code">Step #5 – Upload the Code</h3>
<p>You can upload the code using the upload button (the button after the verify button).</p>
<p>If there are no errors in your code, these steps will help upload code to your board. If you've uploaded the code above, you should have the built-in LED (it is connected to pin 13 by design) on the Uno board blinking.</p>
<p>In the next chapter, you'll learn the basics of the Arduino programming language.</p>
<h1 id="heading-chapter-2-basics-of-arduino-programming">Chapter 2: Basics of Arduino Programming</h1>
<p>Before we dive into creating our own sketches and tinkering, you have to understand the logic that make these boards work as expected. To do that, you’ll have to know how to code using the Arduino programming language.</p>
<p>As discussed in the last chapter, the Arduino language is built upon C/C++. You’ll begin this chapter by learning the basics of programming. This will prepare you for every other chapter that involves writing code.</p>
<p>I’ve created this chapter with beginners in mind. If you’ve never written code before then this can serve as a starting point for you. This doesn’t mean you’ll learn how to code in C or C++. You’ll be learning how to write Arduino code which shares similar syntax with those languages.</p>
<p>At the end of this chapter, you should be able to understand and write Arduino code.</p>
<h2 id="heading-variables-and-data-types-in-arduino">Variables and Data Types in Arduino</h2>
<p>Variables and data types are used in most programming languages to store and manipulate data. You can think of variables as containers or storage units. Data types, like the name implies, are the type of data stored in variables.</p>
<p>In Arduino programming, you must specify the data type of a variable before using it. That is:</p>
<pre><code>dataType variableName = variableValue
</code></pre><p>There are different types of data types in Arduino, and we’ll discuss each one along with code examples.</p>
<h3 id="heading-int-data-type-in-arduino"><code>int</code> Data Type in Arduino</h3>
<p>The <code>int</code> data type is used to store integer values. The Uno board has a 16-bit integer capacity so it can store values that fall within the range of -32,768 to 32,767.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> redLED = <span class="hljs-number">6</span>;
</code></pre>
<p>In the code above, we created an integer variable called <code>redLED</code> with a value of 6.</p>
<p>The <code>int</code> data type can also store negative integers:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> redLED = <span class="hljs-number">-6</span>;
</code></pre>
<h3 id="heading-long-data-type-in-arduino"><code>long</code> Data Type in Arduino</h3>
<p>The <code>long</code> data type is similar to <code>int</code> but has a wider range of integer values. It has a 32-bit integer limit which falls within the range of -2,147,483,648 to 2,147,483,647.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">long</span> largeNumber = <span class="hljs-number">6000</span>;
</code></pre>
<h3 id="heading-float-data-type-in-arduino"><code>float</code> Data Type in Arduino</h3>
<p>The <code>float</code> data type can be used to store numbers with decimals. Float variables can store values up to 3.4028235E+38 and values as low as -3.4028235E+38.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">float</span> num = <span class="hljs-number">10.5</span>;
</code></pre>
<p>Although the <code>float</code> data type is mainly used for decimal numbers, it can also accept whole numbers (integers without decimals). But it'll always return a float value. So if you store 10 in a <code>float</code>, it'll return 10.00.</p>
<h3 id="heading-string-data-type-in-arduino"><code>String</code> Data Type in Arduino</h3>
<p>You can use the <code>String</code> data type to store and manipulate text. You'll work with strings occasionally to display information in the form of text when building projects.</p>
<p>Here's a code example:</p>
<pre><code class="lang-c++">String greeting = <span class="hljs-string">"Hello World!"</span>;
</code></pre>
<p>The value of strings are nested within double quotation marks as can be seen in the code above.</p>
<p>Note that when declaring a string, the "S" should always be in uppercase.</p>
<h3 id="heading-char-data-type-in-arduino"><code>char</code> Data Type in Arduino</h3>
<p>The <code>char</code>  data type stores single characters.</p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">char</span> alphabet = <span class="hljs-string">'A'</span>;
</code></pre>
<p>This is different from the <code>String</code> data type that can store multiple characters.</p>
<p>There are two main differences between <code>char</code> and <code>String</code>:</p>
<ul>
<li><code>char</code> uses single quotes ('A') while <code>string</code> uses double quotes ("Arduino").</li>
<li><code>char</code> stores single characters while <code>string</code> stores multiple characters.</li>
</ul>
<p><code>char</code> can also accept integer values equivalent to the <a target="_blank" href="https://www.asciitable.com/">ASCII</a> value of letters:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">char</span> charValue = <span class="hljs-number">65</span>;
</code></pre>
<p>In the code above, we initialized a <code>char</code> variable with the value of 65. When printed to the serial monitor (we'll talk about the serial monitor in <a class="post-section-overview" href="#heading-chapter-6-how-to-use-the-serial-monitor-in-arduino-2">Chapter 6: How to use the Serial Monitor in Arduino</a>), A will be returned.</p>
<p>A is returned because 65 has an ASCII character of A.</p>
<h3 id="heading-bool-and-boolean-data-types-in-arduino"><code>bool</code> and <code>boolean</code> Data Types in Arduino</h3>
<p>You can use both <code>bool</code> and <code>boolean</code> to store/denote boolean values of either <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">bool</span> roomIsCold = <span class="hljs-literal">false</span>;
</code></pre>
<p>Boolean values are mostly used with logical and comparison operators, and conditional statements (you'll learn about these later in this chapter) to manipulate and control different outcomes in an Arduino program.</p>
<h3 id="heading-byte-data-type-in-arduino"><code>byte</code> Data Type in Arduino</h3>
<p>The <code>byte</code> data type has an 8-bit unsigned integer limit that ranges from 0 to 255. Unsigned means that it can't store negative values.</p>
<pre><code class="lang-c++">byte sensorValue = <span class="hljs-number">200</span>;
</code></pre>
<p>The <code>byte</code> data type isn't the only data type that can be unsigned. You can also use the <code>unsigned int</code>, <code>unsigned long</code>, and <code>unsigned char</code> data types which all have their respective positive integer ranges.</p>
<h2 id="heading-operators-in-arduino">Operators in Arduino</h2>
<p>Operators are symbols or characters that can be used to perform certain operations on operands. An operand is simply any value(s) an operator acts on.</p>
<p>There are different categories of operators in Arduino like:</p>
<h3 id="heading-arithmetic-operators">Arithmetic Operators</h3>
<p>Arithmetic operators are used to perform mathematical operations like addition, subtraction, division, multiplication, and so on. Here are some arithmetic operators you should know:</p>
<h4 id="heading-addition-operator">Addition(+) Operator</h4>
<p>The addition operator, denoted by the <code>+</code> symbol, adds two operands together:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;

<span class="hljs-comment">// we use addition operator to add a and b below</span>
<span class="hljs-keyword">int</span> c = a + b;

Serial.print(c);
<span class="hljs-comment">// 15</span>
</code></pre>
<h4 id="heading-subtraction-operator">Subtraction(-) Operator</h4>
<p>The subtraction operator subtracts the value of one operand from another operand. It is denoted by the <code>-</code> symbol:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;

<span class="hljs-comment">// we use subtraction operator to subtract b from a below</span>
<span class="hljs-keyword">int</span> c = b - a;

Serial.print(c);
<span class="hljs-comment">// 5</span>
</code></pre>
<h4 id="heading-multiplication-operator">Multiplication (*) Operator</h4>
<p>You can use the multiplication operator (<code>*</code>) to multiply two operands:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;

<span class="hljs-comment">// we use multiplication operator to multiply a by b below</span>
<span class="hljs-keyword">int</span> c = a * b;

Serial.print(c);
<span class="hljs-comment">// 50</span>
</code></pre>
<h4 id="heading-division-operator">Division(/) Operator</h4>
<p>The division operator divides one operand by another:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;

<span class="hljs-comment">// we use division operator to divide b by a below</span>
<span class="hljs-keyword">int</span> c = b / a;

Serial.print(c);
<span class="hljs-comment">// 2</span>
</code></pre>
<h4 id="heading-modulus-operator">Modulus (%) Operator</h4>
<p>The modulus operator returns the remainder of a division between two operands:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;

<span class="hljs-comment">// we use division operator to divide b by a below</span>
<span class="hljs-keyword">int</span> c = b % a;

Serial.print(c);
<span class="hljs-comment">// 0</span>
</code></pre>
<h4 id="heading-increment-operator">Increment (++) Operator</h4>
<p>The increment operator increases the value of a variable by 1:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> num = <span class="hljs-number">5</span>;
num++;

Serial.print(num);
<span class="hljs-comment">// 6</span>
</code></pre>
<h4 id="heading-decrement-operator">Decrement (--) Operator</h4>
<p>The decrement operator decreases the value of a variable by 1:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> num = <span class="hljs-number">5</span>;
num--;

Serial.print(num);
<span class="hljs-comment">// 4</span>
</code></pre>
<h3 id="heading-assignment-operators">Assignment Operators</h3>
<p>Assignment operators are mainly used to assign values to variables. You can also use them to update the value of variables. </p>
<p>The assignment (<code>=</code>) operator is used for assigning and updating variables. The <code>=</code> operator should not be confused for "equal to" — they aren't the same. We'll talk about the equal to (<code>==</code>) operator in the Comparison Operators section.</p>
<p>Here's an example that shows how to use the assignment operator:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> age = <span class="hljs-number">1</span>;
</code></pre>
<p>In the code above, we created a variable called <code>age</code>, and then assigned a value of 1 to it using the <code>=</code> operator.</p>
<p>But this isn't the only way to assign or update the value of variables when using the <code>=</code> operator. You can also use compound assignment operators.</p>
<h4 id="heading-compound-assignment-operators">Compound Assignment Operators</h4>
<p>Compound assignment operators let you combine arithmetic operators and the <code>=</code> operator. This method provides a shorter way of writing code. Here is an example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
x += <span class="hljs-number">5</span>;

Serial.print(x)
<span class="hljs-comment">// 10</span>
</code></pre>
<p>In the code above, we created an <code>x</code> variable and assigned a value of 5 to it. But on the second line, you'd see that we combined the arithmetic addition (<code>+</code>) operator and the <code>=</code> operator to assign a new value to <code>x</code>:</p>
<pre><code class="lang-c++">x += <span class="hljs-number">5</span>;
</code></pre>
<p>The line of code above is the same as this:</p>
<pre><code class="lang-c++">x = x + <span class="hljs-number">5</span>;
</code></pre>
<p>So compound operators combine two operators and let you do the same thing in a shorter way. There's nothing wrong with either method.</p>
<p>Here are other compound operator examples:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> a = <span class="hljs-number">10</span>;
a -= <span class="hljs-number">5</span>; <span class="hljs-comment">// Equivalent to a = a - 5 (a becomes 5)</span>

<span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;
b *= <span class="hljs-number">5</span>; <span class="hljs-comment">// Equivalent to b = b * 5 (b becomes 50)</span>

<span class="hljs-keyword">int</span> c = <span class="hljs-number">10</span>;
c /= <span class="hljs-number">5</span>; <span class="hljs-comment">// Equivalent to c = c / 5 (c becomes 2)</span>

<span class="hljs-keyword">int</span> d = <span class="hljs-number">10</span>;
d %= <span class="hljs-number">5</span>; <span class="hljs-comment">// Equivalent to d = d % 3 (d becomes 0)</span>
</code></pre>
<h3 id="heading-comparison-operators">Comparison Operators</h3>
<p>You can use comparison operators to compare two values/operands. Comparison operators return either <code>true</code> (1) or <code>false</code> (0) depending on the relationship between operands.</p>
<p>Comparison operators can help you make decisions based on their return values. You'll see them a lot when we start building projects.</p>
<p>Here are the comparison operators you'll come across occasionally:</p>
<h4 id="heading-equal-to-operator">Equal To (==) Operator</h4>
<p>This operator compares the values of two variables. If the values are the same, it returns <code>true</code>. If the values are not the same, it returns <code>false</code>. Here's an example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>; 

Serial.print(x == y)
<span class="hljs-comment">// returns 0</span>
</code></pre>
<p>The return value of <code>x == y</code> in the code above is 0 (<code>false</code>) because the two variables are not the same. Remember that the <code>==</code> operator returns 1 (<code>true</code>) only when both variables have the same value.</p>
<h4 id="heading-not-equal-operator">Not Equal (!=) Operator</h4>
<p>The not equal operator checks whether two values have different values. It's does the opposite of the <code>==</code> operator. That means it'll return 1 (<code>true</code>) if both values are not of the same value and 0 (<code>false</code>) if both values are the same.</p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>; 

Serial.print(x != y)
<span class="hljs-comment">// returns 1</span>
</code></pre>
<h4 id="heading-greater-than-gt-operator">Greater Than (&gt;) Operator</h4>
<p>The greater than (<code>&gt;</code>) operator checks if the operand on the left is greater than the operand on the right. If the left operand is greater, it returns 1. If the left operand is smaller, it returns 0.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>; 

Serial.print(x &gt; y)
<span class="hljs-comment">// returns 1</span>
</code></pre>
<h4 id="heading-less-than-lt-operator">Less Than (&lt;) Operator</h4>
<p>The less than (<code>&lt;</code>) operator checks if the operand on the left is less than the operand on the left. If the left operand is smaller, it returns 1. If the left operand is greater, it returns 0.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>; 

Serial.print(x &lt; y)
<span class="hljs-comment">// returns 0</span>
</code></pre>
<h4 id="heading-greater-than-or-equal-to-gt-operator">Greater Than or Equal To (&gt;=) Operator</h4>
<p>Just like the name, the <code>&gt;=</code> operator checks if the operand on the left is either greater than or equal to the operand on the right. It returns 1 if the left operand is greater than or equal to the right operand, and 0 if it isn't.</p>
<p>"Or" implies that either of the conditions can be used. If the left operand is not greater than the right operand but is equal to the right operand, you'll still get a value of 1.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>; 

Serial.print(x &gt;= y)
<span class="hljs-comment">// returns 1</span>
</code></pre>
<h4 id="heading-less-than-or-equal-to-lt-operator">Less Than or Equal To (&lt;=) Operator</h4>
<p>The <code>&lt;=</code> operator checks if the left operand is either less than or equal to the right operand. If the left operand is less than or equal to the right operand, it returns 1, and returns 0 if the left operand is neither less than nor equal to the right operand.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">int</span> y = <span class="hljs-number">5</span>; 

Serial.print(x &lt;= y)
<span class="hljs-comment">// returns 0</span>
</code></pre>
<h3 id="heading-ia"> </h3>
<p>Logical Operators</p>
<p>Logical operators are used in most programming languages to evaluate and determine the relationship between variables. </p>
<p>Here are the three logical operators you should know for Arduino programming:</p>
<h4 id="heading-logical-and-ampamp-operator">Logical AND (<code>&amp;&amp;</code>) Operator</h4>
<p>The logical AND (<code>&amp;&amp;</code>) operator returns 1 if both statements are true.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;

Serial.print((x &gt; <span class="hljs-number">5</span>) &amp;&amp; (x &gt; <span class="hljs-number">3</span>));
<span class="hljs-comment">// returns 1</span>
</code></pre>
<p>The expression above — <code>(x &gt; 5) &amp;&amp; (x &gt; 3)</code> — returns 1 because both statements are true. That is, <code>x &gt; 3</code> and <code>x &gt; 3</code>. If either or both of those statements were false, then we'd have a return value of 0.</p>
<h4 id="heading-logical-or-operator">Logical OR (||) Operator</h4>
<p>The logical OR (<code>||</code>) operator returns 1 if one of both statements is true.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;

Serial.print((x &gt; <span class="hljs-number">5</span>) &amp;&amp; (x &gt; <span class="hljs-number">15</span>));
<span class="hljs-comment">// returns 1</span>
</code></pre>
<p>The code above returns 1 although one of the statements is false. This is because the <code>||</code> operator returns 1 if either or both statements are true.</p>
<h4 id="heading-logical-not-operator">Logical NOT (!) Operator</h4>
<p>The NOT (<code>!</code>) operator negates or reverses the value of its operand. If the operand statement is true, it returns false, and returns false if the operand is true.</p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">10</span>;

Serial.print(!(x &gt; <span class="hljs-number">5</span>));
<span class="hljs-comment">// returns 0</span>
</code></pre>
<p>The code above returns 0, but why? <code>x &gt; 5</code> is true so the expected result is 1.</p>
<p>We got 0 because the <code>!</code> operator reversed the return value of the operand from 0 to 1.</p>
<h2 id="heading-conditional-statements-in-arduino">Conditional Statements in Arduino</h2>
<p>You can use conditional statements to make decisions or execute code based on specific conditions. You can combine conditional statements and logic (like operators in the last section) to control how code is executed.</p>
<p>Let's take a look at some conditional statements and how to use them:</p>
<h3 id="heading-if-statement"><code>if</code> Statement</h3>
<p>The <code>if</code> statement is used to execute code if a condition is <code>true</code>. Here's what the syntax looks like:</p>
<pre><code><span class="hljs-keyword">if</span> (condition) {
    <span class="hljs-comment">// code to be executed if condition is true</span>
}
</code></pre><p>In the syntax above, <code>condition</code> denotes a specified logic. If the condition is <code>true</code> then the code in the curly brackets will be executed. Here's an example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
<span class="hljs-keyword">if</span> (x &lt; <span class="hljs-number">10</span>) {
  Serial.print(<span class="hljs-string">"x is less than 10"</span>);
}

<span class="hljs-comment">// x is less than 10</span>
</code></pre>
<p>In the code above, we gave a condition— <code>x &lt; 10</code> — and a block of code within curly brackets that prints "x is less than 10". The code in the curly brackets will only run if the condition is true.</p>
<p>This is the same as saying "if x is less than 10 then print 'x is less than 10' to the serial monitor". Since x is less than 10, the condition evaluates as <code>true</code> and we get the message printed out.</p>
<p>But what if the condition is <code>false</code>? The code in the curly brackets won't run, so we'll need a different type of logic to handle situations like that. We can do this using the <code>else</code> statement.</p>
<h3 id="heading-else-statement"><code>else</code> Statement</h3>
<p>The <code>else</code> statement is used to execute code if a condition is <code>false</code>.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> score = <span class="hljs-number">20</span>;
<span class="hljs-keyword">if</span> (score &gt; <span class="hljs-number">50</span> ) {
  Serial.print(<span class="hljs-string">"You passed the exam!"</span>);
} <span class="hljs-keyword">else</span> {
  Serial.print(<span class="hljs-string">"You have to rewrite the exam!"</span>);
}

<span class="hljs-comment">// You have to rewrite the exam</span>
</code></pre>
<p>In the code above, the condition given is <code>false</code>. So the code for the <code>else</code> statement will be executed because the <code>score</code> variable is not greater than 50.</p>
<p>Remember: the code for the <code>else</code> statement only runs when the condition is <code>false</code>. If the condition is <code>true</code> then the code for the <code>if</code> statement will be executed.</p>
<h3 id="heading-else-if-statement"><code>else if</code> Statement</h3>
<p>You can use the <code>else if</code> statement to define multiple conditions to be checked. Here's the syntax:</p>
<pre><code><span class="hljs-keyword">if</span> (condition1) {
    <span class="hljs-comment">// code to be executed if condition1 is true</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (condition2){
    <span class="hljs-comment">// code to be executed if condition2 is true</span>
} <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// code to be executed if condition1 and condition2 are false</span>
}
</code></pre><p>In the syntax above, there are two conditions (you can create more than two conditions). If <code>condition1</code> is <code>true</code>, then code in the curly bracket for <code>condition1</code> will be executed.</p>
<p>If condition1 is <code>false</code>, then <code>condition2</code> will be evaluated. If <code>condition2</code> is <code>true</code>, its block of code will be executed.</p>
<p>If both <code>condition1</code> and <code>condition2</code> are <code>false</code>, the <code>else</code> statement's code will be executed.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> score = <span class="hljs-number">80</span>;
<span class="hljs-keyword">if</span> (score &gt; <span class="hljs-number">50</span> ) {
  Serial.print(<span class="hljs-string">"You passed the exam!"</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (score &lt; <span class="hljs-number">50</span>) {
  Serial.print(<span class="hljs-string">"You have to rewrite the exam!"</span>);
} <span class="hljs-keyword">else</span> {
  Serial.print(<span class="hljs-string">"No records for your exam score found!"</span>);
}

<span class="hljs-comment">// You passed the exam!</span>
</code></pre>
<h3 id="heading-switch-case-statement"><code>switch-case</code> Statement</h3>
<p>In the last section, we saw how to create multiple conditions using <code>else if</code> statements. Your code might become hard to read if you have many conditions. We can clean it up and make the code more readable using <code>switch</code> statements.</p>
<p>Here's what the syntax looks like:</p>
<pre><code><span class="hljs-keyword">switch</span> (expression) {
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
        <span class="hljs-comment">// Code to be executed if expression equals case 1</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
        <span class="hljs-comment">// Code to be executed if expression equals case 2</span>
        <span class="hljs-keyword">break</span>;
     <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
        <span class="hljs-comment">// Code to be executed if expression equals case 3</span>
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">default</span>:
        <span class="hljs-comment">// Code to be executed if expression doesn't match any case</span>
        <span class="hljs-keyword">break</span>;
}
</code></pre><p>Let's break the syntax down:</p>
<ul>
<li>The <code>expression</code> is compared to the value of each <code>case</code>.</li>
<li>When a <code>case</code> matches the <code>expression</code>, the code for that case is executed.</li>
<li>The <code>break</code> keyword stops the <code>switch</code> statement's iteration once a match for the <code>expression</code> has been found.</li>
<li>The code for the <code>default</code> keyword is executed if none of the cases match the <code>expression</code>.</li>
</ul>
<p>Here's an example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> day = <span class="hljs-number">2</span>;

<span class="hljs-keyword">switch</span> (day) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    Serial.print(<span class="hljs-string">"Monday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
    Serial.print(<span class="hljs-string">"Tuesday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">3</span>:
    Serial.print(<span class="hljs-string">"Wednesday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">4</span>:
    Serial.print(<span class="hljs-string">"Thursday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">5</span>:
    Serial.print(<span class="hljs-string">"Friday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">6</span>:
    Serial.print(<span class="hljs-string">"Saturday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> <span class="hljs-number">7</span>:
    Serial.print(<span class="hljs-string">"Sunday"</span>);
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    Serial.print(<span class="hljs-string">"Number out of range"</span>);
  }

<span class="hljs-comment">//  Tuesday</span>
</code></pre>
<p>The code above prints "Tuesday" because the <code>expression</code> which has a value of 2 matches <code>case 2</code>.</p>
<h2 id="heading-loops-in-arduino">Loops in Arduino</h2>
<p>You can use loops to execute code repeatedly until a certain condition is met. You can also use loops to iterate over a collection of data and execute code on all elements of the collection.</p>
<p>There are different type of loops you can use in Arduino like the <code>for loop</code>, <code>while loop</code>, and <code>do-while</code> loop. Let's take a look at their syntax along with some practical examples:</p>
<h3 id="heading-for-loop"><code>for</code> loop</h3>
<p>You can use the <code>for loop</code> to iterate through a collection or execute code until a certain condition is met. It is commonly used when you know the number of times the loop is supposed to run.</p>
<p>Here's the syntax:</p>
<pre><code><span class="hljs-keyword">for</span> (initialization; condition; increment/decrement) {
   <span class="hljs-comment">// code to be executed</span>
}
</code></pre><p>There are three important keywords in the syntax above:</p>
<ul>
<li><strong>initialization</strong> denotes an initial variable (usually an integer) which specifies the starting point of the loop.</li>
<li><strong>condition</strong> is used to control the number of times the loop is expected to run for. The loop stops when the condition is <code>false</code>.</li>
<li><strong>increment/decrement</strong> increases/decreases the value of the initial variable after every iteration.</li>
</ul>
<p>Here's an example to help you understand the keywords:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">11</span>; i++){
  Serial.println(i);
}

<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// 6</span>
<span class="hljs-comment">// 7</span>
<span class="hljs-comment">// 8</span>
<span class="hljs-comment">// 9</span>
<span class="hljs-comment">// 10</span>
</code></pre>
<p>In the loop above, we created an initial variable called <code>1</code> with a value of 0.</p>
<p>The condition stated <code>i &lt; 11</code> which implies that the loop will continue to run as long as <code>i</code> is less than 11.</p>
<p>Using the increment operator <code>i++</code>, we increased the value of <code>i</code> by 1 every time the loop ran.</p>
<p>Lastly, we printed the value of <code>i</code> at every iteration. In the serial monitor, you'll notice the numbers from 0 to 10 printed out. This is because after the number 10, <code>i</code> is no longer less than 11 (the condition given), so the loop terminates.</p>
<h3 id="heading-while-loop"><code>while</code> loop</h3>
<p>The <code>while</code> loop works just like the <code>for</code> loop — it executes code as long as the given condition is <code>true</code>. But its often used when the number of times the loop is supposed to run is unknown.</p>
<p>Here's the syntax:</p>
<pre><code><span class="hljs-keyword">while</span> (condition) {
    <span class="hljs-comment">// Code to be executed</span>
}
</code></pre><p>In the syntax above, the code will continue to run until the <code>condition</code> becomes <code>false</code>.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">11</span>) {
  Serial.println(i);
  i++;
}

<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// 6</span>
<span class="hljs-comment">// 7</span>
<span class="hljs-comment">// 8</span>
<span class="hljs-comment">// 9</span>
<span class="hljs-comment">// 10</span>
</code></pre>
<h3 id="heading-do-while-loop"><code>do-while</code> Loop</h3>
<p>The <code>do-while</code> loop is just like the <code>while</code> loop, but it executes its code block first before checking the validity of the condition given. That is, at the beginning of the loop, the code in curly brackets will run first even if the condition is <code>false</code>. After that, it starts checking if the condition is <code>true</code> or <code>false</code>, just like a normal loop.</p>
<p>In summary, the code for a <code>do-while</code> loop will run at least once, irrespective of the condition given. Here's an example:</p>
<pre><code><span class="hljs-keyword">do</span> {
  <span class="hljs-comment">// code block to be executed</span>
}
<span class="hljs-keyword">while</span> (condition);
</code></pre><p>Here's the code example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">do</span> {
  Serial.println(i);
  i++;
} <span class="hljs-keyword">while</span> ( i &lt; <span class="hljs-number">11</span>);

<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// 6</span>
<span class="hljs-comment">// 7</span>
<span class="hljs-comment">// 8</span>
<span class="hljs-comment">// 9</span>
<span class="hljs-comment">// 10</span>
</code></pre>
<h2 id="heading-arrays-in-arduino">Arrays in Arduino</h2>
<p>You can use arrays in Arduino to store multiple variables of the same data type in a single variable. Each element stored in an array can be accessed using its index number.</p>
<h3 id="heading-array-declaration">Array Declaration</h3>
<p>Declaring an array simply means to create one. You can do that in Arduino using the syntax below:</p>
<pre><code>dataType arrayName[arraySize]
</code></pre><p>In the syntax above:</p>
<ul>
<li><code>dataType</code> represents the data types that'll be stored in the array. For instance, if the data type is <code>int</code>, then only integers can be stored in the array.</li>
<li><code>arrayName</code> denotes the name of the array.</li>
<li><code>arraySize</code> denotes the number of elements that can be stored in the array.</li>
</ul>
<p>Here's an array declaration code example:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> ages[<span class="hljs-number">4</span>];
</code></pre>
<p>In the code above, we created an array called <code>ages</code>. The array can only store four elements with an <code>int</code> data type.</p>
<h3 id="heading-array-initialization">Array Initialization</h3>
<p>To initialize an array means to assign values to the array. In the last section, we created an array called <code>ages</code>. Now, let's assign some elements to it:</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> ages[<span class="hljs-number">4</span>] = {<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>};
</code></pre>
<p>You can see from the example above that there are only four elements in the array — 2, 4, 6, 8. Assigning a fifth element would throw an error because we specified that the array can only have for integer elements: <code>int ages[4];</code>.</p>
<p>You can access the elements of the array using their index number. Indexes start at zero (0) – so the first element has an index of 0, the second element has an index of 1, the third element has an index of 2, and so on.</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> ages[<span class="hljs-number">4</span>] = {<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>};

Serial.print(ages[<span class="hljs-number">0</span>]);
<span class="hljs-comment">// 2</span>
</code></pre>
<p>As can be seen above, we accessed the first element using the array name and the index of the element in square brackets: <code>ages[0]</code>.</p>
<p>You can also assign and reassign values to a particular element using its index:</p>
<pre><code class="lang-c++">ages[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>;
</code></pre>
<p>Note that you can declare and initialize an array at the same time. I only divided them into separate sections to help you understand what each term means.</p>
<h2 id="heading-functions-in-arduino">Functions in Arduino</h2>
<p>In the last chapter, we discussed some built-in functions in Arduino that can be used to carry out a variety of tasks related to Arduino hardware and software components. All we did was write the function name and pass in parameters where necessary and we got the desired outcome.</p>
<p>For instance, the <code>digitalWrite()</code> function writes values to digital pins using two parameters (the pin number and the value to be sent to the pin). Under the hood, some code logic handles that operation.</p>
<p>Let's assume that the logic required to send values to digital pins was up to a hundred lines of code. Without functions, you'll have to write those hundred lines every time you wanted to send values to digital pins.</p>
<p>Functions prevent you from having to reinvent the wheel. They also help you break your code down into smaller, more readable and manageable parts.</p>
<p>Just like how built-in functions can be reused to perform a particular task repeatedly, you can also create your own functions for specific functionalities, and that's exactly what you'll learn in this chapter.</p>
<h3 id="heading-how-to-declare-functions-in-arduino">How to Declare Functions in Arduino</h3>
<p>There are four main parts of a function in Arduino:</p>
<ul>
<li>The type of data the function returns.</li>
<li>The name of the function.</li>
<li>The function parameter(s) which is optional.</li>
<li>The body of the function.</li>
</ul>
<p>Here's what that looks like:</p>
<pre><code>dataType functionName(optionalParameters) {
    <span class="hljs-comment">// body of the function</span>
}
</code></pre><p>So from the syntax above, <code>dataType</code> is the data type the function returns. It can be <code>int</code>, <code>String</code>, and so on. A function that has no <code>return</code> statement uses the <code>void</code> type as its data type.</p>
<p>The <code>functionName</code> is the name given to the function. The name is used to call the function to execute the logic defined in the body of the function. You'd see words like "call", "fire", and "invoke" associated with functions. They all mean the same thing — to execute the function's logic.</p>
<p><code>optionalParameters</code> are variables that you define when creating a function. They enable functions to accept external data which can be used within the function body. Function parameters are defined along with their data types. You'll understand this when we look at some examples.</p>
<p>The body of the function is where all the logic goes to. What the function does when it is invoked is written in the body.</p>
<p>Now that we've seen the different parts of a function, let's create some functions!</p>
<h3 id="heading-how-to-declare-a-function-with-the-void-type">How to Declare a Function with the <code>void</code> Type</h3>
<p>In the last chapter, we discussed the <code>void Setup()</code> and <code>void loop()</code> functions. They are two built-in functions that you'll use in every Arduino sketch. These functions are defined using the <code>void</code> keyword because they return nothing</p>
<p>Here's what the syntax looks like for functions that use the <code>void</code> type:</p>
<pre><code><span class="hljs-keyword">void</span> functionName(optionalParameters) {
    <span class="hljs-comment">// code logic</span>
}
</code></pre><p>In the syntax above, <code>functionName</code> denotes the name of the function. We can use that name to call the function in order to execute the code defined in the function.</p>
<p><code>optionalParameters</code> are used to pass external data to the function while the code logic that runs when the function is called is written between the curly brackets.</p>
<p>Here's an example:</p>
<pre><code class="lang-c++"><span class="hljs-comment">// function declaration</span>
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printName</span><span class="hljs-params">(String userName)</span> </span>{
  Serial.println(<span class="hljs-string">"Hello "</span> + userName);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  printName(<span class="hljs-string">"Ihechikara"</span>); <span class="hljs-comment">// function call</span>
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>In the code above, we created a function called <code>printName</code> which accepts a string parameter called <code>userName</code>. The function's task is to print "Hello " along with whatever the parameter value is.</p>
<p>In the <code>void loop()</code>, we called the function and passed a parameter to it: <code>printName("Ihechikara")</code>. In the serial monitor, you'll see "Hello Ihechikara" printed.</p>
<p>To call a function, all you have to do is write the name of the function with parenthesis: <code>printName()</code>. Remember to pass in parameters when required: <code>printName("Ihechikara")</code>.</p>
<p>Using a parameter that has the wrong data type will result in an error. For instance, we defined a string parameter in our example. Using an integer will raise an error because the function expects a string.</p>
<h3 id="heading-how-to-declare-a-function-with-a-return-data-type">How to Declare a Function with a Return Data Type</h3>
<p>In this section, I'll use the <code>int</code> data type to show you how functions declared without the <code>void</code> type are used. The logic here is the same with other functions that use the <code>return</code> statement.</p>
<pre><code class="lang-c++"><span class="hljs-comment">// function declaration</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">addNums</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{

  <span class="hljs-keyword">int</span> result = a + b;
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  Serial.println(addNums(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>)); <span class="hljs-comment">// function call</span>
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>In the code above, we declared a function with the <code>int</code> type: <code>int addNums(int a, int b) {...}</code>. This implies that the function is expected to return an integer value.</p>
<p>The function's logic adds the value of the two parameters (<code>a</code> and <code>b</code>) and returns their sum. We used the <code>return</code> statement to return the sum of the parameters.</p>
<p>We can now say that the task of the <code>addNums</code> function is to return the sum of two given parameters. This can be seen when we used the function in the <code>void loop()</code>:</p>
<pre><code class="lang-c++">Serial.println(addNums(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>));
</code></pre>
<p>We called the function with two parameters and got their sum printed out in the serial monitor.</p>
<h3 id="heading-what-you-should-know-about-the-return-statement">What You Should Know About the <code>return</code> Statement</h3>
<p>In the last two sections, we saw how to use functions in two different ways — functions that use the <code>return</code> statement and functions that don't use it.</p>
<p>But what if you used the <code>return</code> statement in a <code>void</code> function? Would that break the code? The answer is no. I'll explain why.</p>
<p>The main use of the <code>return</code> keyword is to return a value from the function, and then terminate the function. Consider the example below:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">addNums</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{

  <span class="hljs-keyword">int</span> result = a + b;
  Serial.println(result);
  <span class="hljs-keyword">return</span> result;

  <span class="hljs-comment">// This part will be ignored</span>
  Serial.println(<span class="hljs-string">"Hello World"</span>);
}
</code></pre>
<p>The function above takes in two parameters — a and b — and returns their sum. You'll notice that we printed "Hello World" after the <code>return</code> statement. The part of the code that comes after the <code>return</code> statement will not be executed because the function terminates/stops its operation once it sees a <code>return</code> statement.</p>
<p>So you should always remember that anything that comes after the <code>return</code> statement will be ignored.</p>
<p>You can use the <code>return</code> statement in <code>void</code> functions but it is a convention not to. We simply use the <code>void</code> keyword to define functions that have no use for the <code>return</code> statement.</p>
<h2 id="heading-commonly-used-built-in-functions-in-arduino-sketch">Commonly Used Built-in Functions in Arduino Sketch</h2>
<p>In this section, we’ll discuss some of the commonly used built-in functions you’ll come across when writing or reading Arduino code. We'll make use of them in most of the upcoming chapters of this handbook.</p>
<p>We'll begin with the two main parts of an Arduino sketch — the <code>setup()</code> and <code>loop()</code> functions.</p>
<h3 id="heading-setup-and-loop-functions-in-arduino"><code>setup()</code> and <code>loop()</code> Functions in Arduino</h3>
<p>You can use the <code>setup()</code> function to configure analog and digital pins, initialize variables, and do other setup functionalities. The <code>setup()</code> function is executed once — when the board is powered on or reset.</p>
<p>The <code>loop()</code> function runs continuously. This part of the sketch is where you write all the code logic. You can use the <code>loop()</code> function to give the Arduino board instructions on different components and sensors.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-comment">// put your setup code here, to run once:</span>

}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-comment">// put your main code here, to run repeatedly:</span>

}
</code></pre>
<h3 id="heading-pinmode-function-in-arduino"><code>pinMode()</code> Function in Arduino</h3>
<p>The <code>pinMode()</code> function is used to configure pins as input or output pins. It can also be used to configure a resistor to act as either a pull-up or pull-down resistor. You'll understand more about this function in the Sensors and Actuators chapter.</p>
<h4 id="heading-syntax">Syntax</h4>
<pre><code>pinMode(pin, mode)
</code></pre><ul>
<li><code>pin</code> denotes the pin number on an Arduino board.</li>
<li><code>mode</code> denotes the configuration of the <code>pin</code> which can be INPUT, OUTPUT, or INPUT_PULLUP.</li>
</ul>
<h3 id="heading-digitalread-function-in-arduino"><code>digitalRead()</code> Function in Arduino</h3>
<p>You can use the <code>digitalRead()</code> function to read the state of digital pins. It returns either 0 (<code>LOW</code>) or 1 (<code>HIGH</code>).</p>
<h4 id="heading-syntax-1">Syntax</h4>
<pre><code>digitalRead(pin)
</code></pre><p>In the code above, <code>pin</code> denotes the pin number on an Arduino board.</p>
<h3 id="heading-digitalwrite-function-in-arduino"><code>digitalWrite()</code> Function in Arduino</h3>
<p>The <code>digitalWrite()</code> function assigns or writes values (either <code>HIGH</code> or <code>LOW</code>) to digital pins.</p>
<h4 id="heading-syntax-2">Syntax</h4>
<pre><code>digitalWrite(pin, value)
</code></pre><ul>
<li><code>pin</code> denotes the pin number on an Arduino board.</li>
<li><code>value</code> denotes the value to be assigned to <code>pin</code>. Can be <code>HIGH</code> or <code>LOW</code>.</li>
</ul>
<h3 id="heading-analogread-function-in-arduino"><code>analogRead()</code> Function in Arduino</h3>
<p>The <code>analogRead()</code> function reads values from analog pins and returns values that fall within the range of 0 and 1023.</p>
<h4 id="heading-syntax-3">Syntax</h4>
<pre><code>analogRead(pin)
</code></pre><p>In the code above, <code>pin</code> denotes the pin number on an Arduino board.</p>
<h3 id="heading-analogwrite-function-in-arduino"><code>analogWrite()</code> Function in Arduino</h3>
<p>This function writes or assigns an analog value to a pin.</p>
<h4 id="heading-syntax-4">Syntax</h4>
<pre><code>analogWrite(pin, value)
</code></pre><ul>
<li><code>pin</code> denotes the pin number on an Arduino board.</li>
<li><code>value</code> denotes the value to be assigned to <code>pin</code>. Range from 0 to 255.</li>
</ul>
<h2 id="heading-serial-functions-in-arduino">Serial Functions in Arduino</h2>
<p>Serial communication enables an Arduino board to communicate with the computer and other devices using the built-in serial monitor. Here are some of the commonly used functions:</p>
<h3 id="heading-serialbegin"><code>Serial.begin()</code></h3>
<p>The <code>Serial.begin()</code> function initializes serial communication. It is the first function you use when working with the serial monitor. The function takes in a baud rate as its parameter.</p>
<p>In this case, baud rate represents the rate or speed of data transfer in serial communication.</p>
<p>Here's the syntax:</p>
<pre><code>Serial.begin(baudRate)
</code></pre><h3 id="heading-serialprint-and-serialprintln"><code>Serial.print()</code> and <code>Serial.println()</code></h3>
<p>You can use the <code>print()</code> and <code>println()</code> functions to print data to the serial monitor.</p>
<pre><code class="lang-cpp">print(val)
println(val)
</code></pre>
<p>In the code above, <code>val</code> denotes the value to be printed.</p>
<p>We'll talk more about serial communication in <a class="post-section-overview" href="#heading-chapter-6-how-to-use-the-serial-monitor-in-arduino-2">Chapter 6: How to use the Serial Monitor in Arduino</a>.</p>
<h3 id="heading-delay-function-in-arduino"><code>delay()</code> Function in Arduino</h3>
<p>You can use the <code>delay()</code> function to pause the Arduino program for a specified amount of time. Here's what the syntax looks like:</p>
<pre><code>delay(ms)
</code></pre><p>In the code above, <code>ms</code> denotes the specified time in milliseconds.</p>
<h1 id="heading-chapter-3-how-to-use-digital-pins-in-arduino">Chapter 3: How to Use Digital Pins in Arduino</h1>
<p>Digital pins are used to send and receive digital signals in two states — <code>HIGH</code> and <code>LOW</code>. The digital pins on a Arduino board can be configured as either input or output pins.</p>
<p>These states can also be represented using numbers (1 for <code>HIGH</code> and 0 for <code>LOW</code>), or in volts (V) (5V for <code>HIGH</code> and 0V for <code>LOW</code>).</p>
<p>The number and arrangement of pins differ in various Arduino boards, but they serve the same purpose. So if you understand how to use them in this chapter, you won't have a problem working with them in other boards.</p>
<p>The Uno board has 14 digital pins numbered from 0 to 13. Although each pin can be configured to serve as either a digital input or output pin, some of them come with extra functionalities like:</p>
<ul>
<li>Pins 0 (RX) and 1 (TX) enable the Arduino board to communicate serially. RX receives while TX sends.</li>
<li>Pins that have the tilde (~) symbol beside them support PWM (Pulse Width Modulation) signals. This means that you can use these pins like analog pins (to receive analog values).</li>
<li>Pins 2 and 3 can be used for interrupt-based functionalities.</li>
</ul>
<h2 id="heading-how-to-configure-digital-pins-as-input-or-output-pins">How to Configure Digital Pins as Input or Output Pins</h2>
<p>When a digital pin is configured as an INPUT pin, it serves as a point for receiving information from components. This way you get data from sensors, electronic components, and so on.</p>
<p>You can use the <code>pinMode()</code> function to configure a pin to serve as either an INPUT or OUTPUT pin. Note that the pins on an Uno board are set to INPUT by default so if you don't specify prior to using them, they'll serve as input pins.</p>
<p>In this section, you'll learn how to use digital pins as both input and output pins. You'll start by learning about them individually, and then see how to combine input and output signals to build a mini project.</p>
<p>We'll start with INPUT.</p>
<h3 id="heading-digital-pins-as-input">Digital Pins as INPUT</h3>
<p>The information or signal sent to input pins can be read using the <code>digitalRead()</code> function. In this section, you'll learn how to configure and read signals from a digital input pin using different built-in functions.</p>
<p>We'll use the following hardware components:</p>
<ul>
<li>Arduino Uno.</li>
<li>Breadboard.</li>
<li>Pushbutton.</li>
<li>Jumper wires.</li>
</ul>
<p>Here's the diagram for the connection:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/circuit-diagram-digital-input-pushbtn.png" alt="Image" width="600" height="400" loading="lazy">
<em>Configuration diagram – INPUT</em></p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> pushBtn = <span class="hljs-number">7</span>;
<span class="hljs-keyword">int</span> push_btn_state;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  pinMode(pushBtn, INPUT_PULLUP);
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  push_btn_state = digitalRead(pushBtn);
  Serial.println(push_btn_state);
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>Let's break the code down.</p>
<p>We started by creating two integer variables — <code>pushBtn</code> and <code>push_btn_state</code>:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> pushBtn = <span class="hljs-number">7</span>;
<span class="hljs-keyword">int</span> push_btn_state;
</code></pre>
<p><code>pushBtn</code> was assigned a value of 7. We used this value to denote pin 7 on the Arduino board. We declared the <code>push_btn_state</code> variable but didn't assign any value to it because we'll use it to store the value of the push button later.</p>
<p>In our <code>setup()</code> function, we configured the push button to act as an input pin using the <code>pinMode()</code> function:</p>
<pre><code class="lang-cpp">pinMode(pushBtn, INPUT_PULLUP);
</code></pre>
<p>The function took in two parameters — the <code>pushBtn</code> variable which denoted pin 7, and <code>INPUT_PULLUP</code> which sets the pin as an input with a pull-up resistor.</p>
<p>We also initialized the serial monitor using <code>Serial.begin(9600)</code>.</p>
<p>At this point, we've configured the Arduino software and hardware to recognize pin 7 as an input pin.</p>
<p>Next, we used the <code>digitalRead()</code> function to read signals coming from pin 7. Remember the <code>push_btn_state</code> variable we created? That's where we stored the signal:</p>
<pre><code class="lang-cpp">push_btn_state = digitalRead(pushBtn);
</code></pre>
<p>After that, we printed the value being read from pin 7 to the serial monitor using <code>Serial.println(push_btn_state);</code>.</p>
<p>When you open the serial monitor, you'll see 1 being printed out repeatedly. This is the initial state of the pushbutton using a pull-up resistor. When you press down the pushbutton, the value will become 0. When you release the button, the value will become 1.</p>
<p>0 denotes <code>LOW</code> while 1 denotes <code>HIGH</code>. With this example, you should understand how to configure, read, and display signals from an input pin.</p>
<h3 id="heading-digital-pins-as-output">Digital Pins as OUTPUT</h3>
<p>The main use of an output pin is to send out signals. Since we're working with digital output, we can send either <code>HIGH</code> (5V) or <code>LOW</code> (0V) signals. We can do this for digital pins using the <code>digitalWrite()</code> function.</p>
<p>In this section, we'll use a LED (Light Emitting Diode) to demonstrate how to configure and send signals to components.</p>
<p>Here are the components we'll use:</p>
<ul>
<li>Arduino Uno.</li>
<li>Red LED.</li>
<li>1k Ohm resistor.</li>
<li>Jumper wires.</li>
<li>Breadboard.</li>
</ul>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/circuit-diagram-digital-output-led.png" alt="Image" width="600" height="400" loading="lazy">
<em>Configuration diagram – OUTPUT</em></p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> RedLED = <span class="hljs-number">8</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  pinMode(RedLED, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  digitalWrite(RedLED, HIGH);
  delay(<span class="hljs-number">1000</span>);
  digitalWrite(RedLED, LOW);
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>In the code above, we configured the red LED, which is connected to pin 8 on the Uno board, as an output pin using the <code>pinMode()</code> function.</p>
<p>We then used the <code>digitalWrite()</code> function to send signals to the pin:</p>
<pre><code class="lang-cpp">  digitalWrite(RedLED, HIGH);
  delay(<span class="hljs-number">1000</span>);
  digitalWrite(RedLED, LOW);
  delay(<span class="hljs-number">1000</span>);
</code></pre>
<p>With the <code>HIGH</code> parameter, we send 5V to the pin which makes the LED come on. With <code>LOW</code>, we send 0V which turns the LED off. So the LED comes on and off continuously with a delay of 1000 milliseconds. This example is commonly known as the "BLINK" example.</p>
<h2 id="heading-digital-io-project">Digital I/O Project</h2>
<p>Now that we've understood how to send and receive digital signals using Arduino, let's combine both of them to build an interactive project.</p>
<p>The idea is to control an LED using a pushbutton. When you press the button, the LED goes off, and comes back on when you release the button.</p>
<p>We'll combine the components used in the previous examples:</p>
<ul>
<li>Arduino Uno.</li>
<li>Red LED.</li>
<li>1k Ohm resistor.</li>
<li>Pushbutton.</li>
<li>Jumper wires.</li>
<li>Breadboard.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/digital-IO-project.png" alt="digital-IO-project" width="600" height="400" loading="lazy">
<em>Configuration diagram - INPUT and OUTPUT project</em></p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> pushBtn = <span class="hljs-number">7</span>;
<span class="hljs-keyword">int</span> push_btn_state;
<span class="hljs-keyword">int</span> RedLED = <span class="hljs-number">8</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  pinMode(pushBtn, INPUT_PULLUP);
  pinMode(RedLED, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  push_btn_state = digitalRead(pushBtn);

  <span class="hljs-keyword">if</span> (push_btn_state == <span class="hljs-number">1</span>) {
    digitalWrite(RedLED, HIGH);
  } <span class="hljs-keyword">else</span> {
    digitalWrite(RedLED, LOW);
  }
}
</code></pre>
<p>Here's a breakdown of the code above:</p>
<p>First, we connected the pushbutton to pin 7 and the red LED to pin 8.</p>
<p>Then we configured both pins — pin 7 as input, and pin 8 as output.</p>
<p>Next, we read the value of the pushbutton using the <code>digitalRead()</code> function and stored the value in a variable called <code>push_btn_state</code>.</p>
<p>Using an <code>if</code> statement, we checked for the state of the pushbutton. When <code>push_btn_state</code> is not being pushed down, it has a value of 1 (<code>HIGH</code>). We send 5V to the LED using <code>digitalWrite()</code>.</p>
<p>When <code>push_btn_state</code> is pushed down, it has a value of 0, and we send 0V to the LED which turns it off.</p>
<h1 id="heading-chapter-4-how-to-use-analog-pins-in-arduino">Chapter 4: How to Use Analog Pins in Arduino</h1>
<p>Analog pins can be used to receive and send voltage values from/to different sensors and components. Unlike digital signals that fall within two states of 0 (<code>LOW</code>) and 1 (<code>HIGH</code>), analog values have a wider range of values from 0 to 1023.</p>
<p>The Uno board has six analog pins — A0, A1, A2, A3, A4, and A5. These pins are INPUT pins by default.</p>
<p>Similar to digital pins, there are in-built functions for receiving and sending analog voltage signals. You can use the <code>analogRead()</code> function to read/receive analog values from pins while the <code>analogWrite()</code> function can be used to write to specific pins.</p>
<p>Note that the <code>analogWrite()</code> function doesn't write or send analog values to analog pins. It sends analog voltage values (that get converted to digital signals) to digital pins that support PWM (Pulse Width Modulation).</p>
<p>You can find PWM digital pins on the Arduino board by the (~) symbol beside them. On the Uno board, there are pins 3, 5, 6, 9, 10, and 11.</p>
<p>In the project for this section, you'll learn how to adjust the brightness of an LED using a potentiometer. We'll use the potentiometer as an input component, and send its voltage to an LED to increase/decrease the LED's brightness.</p>
<p>Here are the components we'll use:</p>
<ul>
<li>Arduino Uno.</li>
<li>Yellow LED.</li>
<li>Potentiometer.</li>
<li>1k Ohm resistor.</li>
<li>Jumper wires.</li>
<li>Breadboard.</li>
</ul>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/analog-IO.png" alt="Image" width="600" height="400" loading="lazy">
<em>Configuration diagram</em></p>
<p>Here's the code for the circuit:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> potentiometer = A0;
<span class="hljs-keyword">int</span> pot_value = <span class="hljs-number">0</span>;
<span class="hljs-keyword">float</span> pot_in_PWM;
<span class="hljs-keyword">int</span> yelowLED = <span class="hljs-number">6</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  pinMode(potentiometer, INPUT);
  pinMode(yelowLED, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  pot_value = analogRead(potentiometer);
  pot_in_PWM = pot_value * (<span class="hljs-number">255.0</span> / <span class="hljs-number">1023.0</span>);

  analogWrite(yelowLED, pot_in_PWM);
}
</code></pre>
<p>In the code above, we set the potentiometer (connected to analog pin A0) as an input component. The yellow LED (connected to digital pin 6) was set as an output component. The LED is connected to a PWM pin because we'll be sending analog values to it.</p>
<p>Using the <code>analogRead()</code> function, we got the value of the potentiometer and stored it in a variable called <code>pot_value</code>. The potentiometer returns values from 0 to 1023.</p>
<p>We then converted the values returned by the potentiometer to a range of 0 to 255 which corresponds with PWM values. This is because the <code>analogWrite()</code> function sends PWM values that fall within that range (0 to 255). The new range of values was stored in a variable called <code>pot_in_PWM</code>.</p>
<p>Lastly, we used the <code>analogRead()</code> function to send PWM values to the LED: <code>analogWrite(yelowLED, pot_in_PWM)</code>.</p>
<p>When you verify and upload the code to your Arduino board, you'll be able to control the brightness of the LED by turning the potentiometer's knob.</p>
<h1 id="heading-chapter-5-how-to-use-sensors-and-actuators-in-arduino">Chapter 5: How to Use Sensors and Actuators in Arduino</h1>
<p>Sensors and actuators play a crucial role in developing projects using Arduino. They help microcontrollers get information about changes in the physical environment, and make decisions based on that information.</p>
<p>The goal of this chapter is to help you understand the difference between sensors and actuators, and how to use them. Of course, there are numerous sensors and actuators, but we'll focus on just a few. You should be able to explore other sensors on your own at the end of this chapter.</p>
<p>We'll first talk about what sensors are, types of sensors, and how to work with them using code. We'll then do the same for actuators, and conclude by looking at an example that uses both sensors and actuators in a project.</p>
<p>Let's get started!</p>
<h2 id="heading-what-are-sensors-in-arduino">What are Sensors in Arduino?</h2>
<p>A sensor is a device that listens for or detects changes in the environment. Sensors convert the information they detect in the physical environment to electrical signals which are then sent to the microcontroller (the brain of the board).</p>
<p>You can look at sensors like the human sense organs — we use them to gather information about our environment. Each sense organ (like eyes and ears) in the human body has a specific function and mode of operation that's different from other organs.</p>
<p>In the same manner, sensors in Arduino have their specific functions and use cases. For example, we have sensors that can measure and detect temperature, motion, moisture, and so on.</p>
<h3 id="heading-types-of-sensors-in-arduino">Types of Sensors in Arduino</h3>
<p>Here are some commonly used sensors you'll come across when working with Arduino:</p>
<ul>
<li><strong>Temperature sensor</strong>: Measures the temperature and humidity of the environment.</li>
<li><strong>Light-Dependent Resistor (LDR)</strong>: Measures/senses the intensity of light.</li>
<li><strong>Ultrasonic sensor</strong>: Measures the distance of an object from the sensor.</li>
<li><strong>Motion sensor</strong>: Generally detects motion by sensing changes in infrared energy/radiation.</li>
<li><strong>Soil moisture sensor</strong>: Measures the moisture level of the soil.</li>
<li><strong>Water sensor</strong>: Measures water level/detects water, and so on.</li>
</ul>
<p>There are other types of sensors that you can use with Arduino, but we'll just focus on two: the LDR (light-dependent resistor) and ultrasonic sensor. </p>
<p>With the examples in this section, you'll be able to explore how other sensors work on your own.</p>
<h3 id="heading-how-to-use-the-light-dependent-resistor-ldr-in-arduino">How to use the Light-Dependent Resistor (LDR) in Arduino</h3>
<p>The light-dependent resistor (LDR), also known as a photoresistor, is an electronic component that has varying levels of resistance depending on the intensity of light.</p>
<p>Basically, you can use this sensor to sense light. You can do cool things with it like creating an automated lighting system that turns on electric lights in your house when it's dark, or a weather station that tracks and monitors sunlight, and so on.</p>
<p>A LDR usually looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/ldr.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram of an LDR</em></p>
<p>Here's what the circuit connection looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/ldr-circuit.png" alt="Image" width="600" height="400" loading="lazy">
<em>Configuration diagram</em></p>
<p>In the circuit above, one leg of the LDR is connected to 5V (volts). The other leg is connected to a 1K Ohm resistor — one end of the resistor is connected to ground (GND) while the other end is connected to an analog pin (A1 in our circuit).</p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> ldrPin = A1;
<span class="hljs-keyword">int</span> ldrValue;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(ldrPin, INPUT);
  Serial.begin(<span class="hljs-number">9600</span>); 
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  ldrValue = analogRead(ldrPin);
  Serial.println(ldrValue);
  delay(<span class="hljs-number">1000</span>); 
}
</code></pre>
<p>In the code above, we created a variable called <code>ldrpin</code> with a value of <code>A1</code>. This denotes the connection made in the circuit where one leg of the LDR is connected to the analog pin. This pin will help us know the value of the sensor.</p>
<p>We then created an <code>ldrValue</code> variable which will be used to store the value of the sensor.</p>
<p>In the <code>setup()</code> function, we set the LDR as an INPUT pin. We also initialized the serial monitor.</p>
<p>Next, we read the value of the LDR using the <code>analogRead</code> function, and stored the value in the <code>ldrValue</code> variable:</p>
<pre><code class="lang-cpp">ldrValue = analogRead(ldrPin);
</code></pre>
<p>Lastly, we printed the read value to the serial monitor with a delay of 1000 milliseconds (one second).</p>
<p>At this point, if you increase the exposure of light on the LDR, the value increases. If you decrease the light intensity or cover the sensor to block off light, the value will decrease or become zero, respectively.</p>
<h2 id="heading-how-to-use-the-ultrasonic-sensor-in-arduino">How to Use the Ultrasonic Sensor in Arduino</h2>
<p>The ultrasonic sensor is generally used to measure the distance of objects. You can use this sensor in a lot of applications like:</p>
<ul>
<li>Home automation (you can perform certain actions when the presence of an object/human is sensed, like turning on lights in a dark room).</li>
<li>Automated doors.</li>
<li>Security systems.</li>
<li>Measurement of distance, and so on.</li>
</ul>
<p>Just like other sensors, there are various types. In this example, we'll use the HC-SR04 ultrasonic sensor. Don't worry, the working principle is the same. So if you understand how to use this one, you can configure and use other types of ultrasonic sensors you come across.</p>
<p>Here's what the circuit diagram looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/ultra-sensor.png" alt="Image" width="600" height="400" loading="lazy">
<em>Configuration diagram (from https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/)</em></p>
<p>The sensor has four pins — VCC, Trig, Echo, and GND.</p>
<ul>
<li>The VCC pin is connected to 5V on the Uno board</li>
<li>The Trig pin is connected to digital pin 9.</li>
<li>The Echo pin is connected to digital pin 10.</li>
<li>The GND pin is connected to GND on the Uno board.</li>
</ul>
<p>The trig pin is used to "trigger" the ultrasonic sensor while the echo pin is used to distance of objects based on the amount of time it takes for ultrasonic waves/signals to bounce back from an object.</p>
<p>Here's a code example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> trigPin = <span class="hljs-number">9</span>; 
<span class="hljs-keyword">int</span> echoPin = <span class="hljs-number">10</span>;  

<span class="hljs-keyword">long</span> duration, distance;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(<span class="hljs-number">10</span>);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = (duration / <span class="hljs-number">2</span>) * <span class="hljs-number">0.0343</span>;

  Serial.print(<span class="hljs-string">"Distance: "</span>);
  Serial.print(distance);
  Serial.println(<span class="hljs-string">" cm"</span>);

  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>In the code above, the trig pin denotes digital pin 9, and the echo pin denotes digital pin 10.</p>
<p>We declared two variables — duration and distance — to be used to store their respective values.</p>
<p>We triggered the sensor by sending the <code>HIGH</code> signal to the trigger pin for 10 microseconds. Without this, the sensor might not work:</p>
<pre><code class="lang-cpp">  digitalWrite(trigPin, HIGH);
  delayMicroseconds(<span class="hljs-number">10</span>);
  digitalWrite(trigPin, LOW);
</code></pre>
<p>We measured and stored the duration of the ultrasonic pulse/signals using the <code>pulseIn(echoPin, HIGH)</code> function and stored it in the <code>duration</code> variable.</p>
<p>We then calculated the duration in centimeters and stored it in the <code>distance</code> variable.</p>
<p>Lastly, we printed the distance to the serial monitor with a delay of 1000 milliseconds.</p>
<p>At this point, you can place an object closer to or farther away from the sensor and see the value of the distance of the object change in the serial monitor.</p>
<h2 id="heading-what-are-actuators-in-arduino">What are Actuators in Arduino?</h2>
<p>Actuators in Arduino are components that convert electrical signals into physical/mechanical motion.</p>
<p>Here are some actuators:</p>
<ul>
<li>LED (Light Emitting Diode): Used as light/visual indicators.</li>
<li>Buzzer: Used to produce sound.</li>
<li>Relay modules: Used to control high voltage devices.</li>
<li>LCD (Liquid Crystal Display): Used as visual display for text, images, sensor data, and so on. We'll dedicate a separate chapter to displays.</li>
<li>Servo motors: Used to control angular or rotational motion (an example is the movement of a robotic arm).</li>
</ul>
<p>We'll focus on the buzzer and LED in this section.</p>
<h3 id="heading-how-to-use-leds-in-arduino">How to use LEDs in Arduino</h3>
<p>LEDs are usually the first components you learn about in Arduino. There are easy to connect and use.</p>
<p>Here's what an LED looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/redLED.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here's the circuit connection:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/led-circuit.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the circuit above, the longer leg of the LED (the anode or positive leg) is connected to digital pin 7. </p>
<p>The shorter leg (cathode) is connected to ground.</p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> redLED = <span class="hljs-number">7</span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(redLED, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  digitalWrite(redLED, HIGH);
  delay(<span class="hljs-number">1000</span>);
  digitalWrite(redLED, LOW);
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>The code above will make the LED blink once the code has been uploaded.</p>
<h3 id="heading-how-to-use-a-buzzer-in-arduino">How to use a Buzzer in Arduino</h3>
<p>You can use buzzers to produce sound. There are generally two types of buzzers: active and passive buzzers.</p>
<p>Active buzzers usually have a predefined type of sound that they produce when voltage is supplied to them. The sound cannot be modified. Active buzzers have an internal circuit that triggers the sound production.</p>
<p>Passive buzzers are a bit more flexible when it comes to producing sound because they rely on external signals. This means that you can determine the frequency (or frequencies) of the sound produced by the buzzer.</p>
<p>Buzzers can be used in different applications like:</p>
<ul>
<li>Alarm systems.</li>
<li>Sound indictor for home appliances.</li>
<li>Doorbells.</li>
<li>Communication devices to denote the start/end of a signal communication, and so on.</li>
</ul>
<p>We'll work with the passive buzzer because of its flexibility. This is what it looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/buzzer.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The buzzer has a positive and negative terminal. The positive is connected to a digital pin while the negative is connected to ground.</p>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/buzzer-circuit.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this example, we'll use the buzzer to produce the DO, RE, MI, FA, SOL, LA, TI music notes sound.</p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> buzzerPin = <span class="hljs-number">7</span>;

<span class="hljs-keyword">int</span> notes[] = {<span class="hljs-number">262</span>, <span class="hljs-number">294</span>, <span class="hljs-number">330</span>, <span class="hljs-number">349</span>, <span class="hljs-number">392</span>, <span class="hljs-number">440</span>, <span class="hljs-number">494</span>};

<span class="hljs-keyword">int</span> noteDurations[] = {<span class="hljs-number">400</span>, <span class="hljs-number">400</span>, <span class="hljs-number">400</span>, <span class="hljs-number">400</span>, <span class="hljs-number">400</span>, <span class="hljs-number">400</span>, <span class="hljs-number">400</span>};

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(buzzerPin, OUTPUT);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">8</span>; i++) {
    tone(buzzerPin, notes[i], noteDurations[i]);
    delay(noteDurations[i] + <span class="hljs-number">50</span>);
    noTone(buzzerPin);
  }

  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>In the code above, we used the <code>buzzerPin</code> variable to denote pin 7 on the Uno board.</p>
<p>We then created an array called <code>notes[]</code> which stores the respective frequency of each note, and another array called <code>noteDurations</code> which stores the duration of each note as they're being produced by the buzzer.</p>
<p>In the <code>void loop()</code> function, we looped through each note a played them using the <code>tone()</code> function. The function takes in three parameters — the pin connected to the buzzer, the frequency, and the duration.</p>
<p>We used the <code>noTone()</code> function to stop the generation of sound. Lastly, we added a delay of 1000 milliseconds which is the amount of time it'll take to play the notes from the start after the last note has been played.</p>
<p>If you've followed along up to this point, then you should have the DO, RE, MI, FA, SOL, LA, TI music notes playing through the buzzer.</p>
<h2 id="heading-arduino-sensor-and-actuator-example">Arduino Sensor and Actuator Example</h2>
<p>Now that you understand what sensors and actuators are and how to use them, let's use them together in one project.</p>
<p>In many embedded systems, sensors and actuators work together to get a specific task/functionality done. Here's how that works:</p>
<ul>
<li>A sensor detects/senses changes in the environment, and sends signals to the microcontroller to notify it of the detected changes.</li>
<li>The microcontroller processes the signals from the sensor. Depending on the existing logic (defined in the code), it sends signals to the actuator.</li>
<li>The actuator converts the signal from the microcontroller to physical/mechanical motion.</li>
</ul>
<p>Let's demonstrate these using an example. The idea here is to turn on an LED in a dark environment and turn it off when there's enough light.</p>
<p>The sensor will be the LDR sensor, the microcontroller will be the Arduino Uno board/software, and the actuator will be the LED.</p>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/ldr-led-circuit.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> redLED = <span class="hljs-number">7</span>;

<span class="hljs-keyword">int</span> ldrPin = A1;
<span class="hljs-keyword">int</span> ldrValue;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(ldrPin, INPUT);
  pinMode(redLED, OUTPUT);
  Serial.begin(<span class="hljs-number">9600</span>); 
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  ldrValue = analogRead(ldrPin);

  <span class="hljs-keyword">if</span> (ldrValue &gt; <span class="hljs-number">200</span>) {
    digitalWrite(redLED, LOW);
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ldrValue &lt; <span class="hljs-number">200</span>) {
    digitalWrite(redLED, HIGH);
  }

  Serial.println(ldrValue);
  delay(<span class="hljs-number">1000</span>); 
}
</code></pre>
<p>As usual, we created variables to represent the Arduino pins connected to the LED and LDR. We then set the LDR as INPUT and the LED as output in the <code>setup()</code> function.</p>
<p>We read the value of the LDR using the <code>analogRead()</code> function and stored it in the <code>ldrValue</code> variable.</p>
<p>Next, we used the an <code>if</code> statement to check the value of the LDR.</p>
<p>If the value is greater than 200, we turn off the LED. If the value is less than 200, we turn on the LED.</p>
<h1 id="heading-chapter-6-how-to-use-the-serial-monitor-in-arduino">Chapter 6: How to Use the Serial Monitor in Arduino</h1>
<p>The serial monitor is a useful tool for every Arduino builder. You can use it for a variety of tasks like:</p>
<ul>
<li>Debugging and testing code/components.</li>
<li>Serial communication between the Arduino board and the computer.</li>
<li>Display sensor and component data and readings.</li>
</ul>
<p>In this chapter, you'll learn how to initialize and use the serial monitor using the Arduino IDE. You'll learn about different built-in functions that can be used to send and receive data between the Arduino board and the computer.</p>
<p>Lastly, you'll build a project that uses values sent from the serial monitor to power specific LEDs connected to the Arduino board.</p>
<h2 id="heading-how-to-initialize-the-serial-monitor-with-serialbegin">How to Initialize the Serial Monitor With <code>Serial.begin()</code></h2>
<p>You can use the <code>Serial.begin()</code> function to initialize the serial monitor. It takes in the baud rate as its parameter. Here's what the syntax looks like:</p>
<pre><code>Serial.begin(baudRate)
</code></pre><p>The baud rate is the speed of data transfer between the Arduino board and the computer or any other device communicating with the Arduino board through the serial monitor.</p>
<p>The most commonly used baud rate is 9600, but you'll also come across resources that make use of 115200, 57600, and 38400, and so on. Whichever baud rate you specify in the <code>Serial.begin()</code> function should always match the baud rate seen in the serial monitor window.</p>
<p>For example, we can initialize the serial monitor in the IDE using the <code>Serial.begin()</code> function like this:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);

}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-comment">// put your main code here, to run repeatedly:</span>

}
</code></pre>
<p>In the code above, using the <code>Serial.begin()</code> function, we initialized the serial monitor in the <code>setup()</code> function with a baud rate of 9600.</p>
<p>At this point, nothing is happening. You can verify that the baud rates match by opening the serial monitor window. Once you have it open, you should have the serial monitor appear at the base of the IDE. You'll see the baud rate of the serial monitor within the window, usually written like "9600 baud".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/baud-rate.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Image showing baud rate</em></p>
<p>If you're using an older version of the IDE, the serial monitor may pop up as a separate window. The functionality is still the same.</p>
<p>Now that we've initialized the serial monitor, let's see how to send and receive data with it.</p>
<h2 id="heading-how-to-send-data-with-serial-monitor">How to Send Data with Serial Monitor</h2>
<p>You can use different built-in functions reserved for serial communication in Arduino. We won't discuss all the built-in serial functions in Arduino – we'll just look at some you'll use/come across regularly. You can see more functions <a target="_blank" href="https://www.arduino.cc/reference/en/language/functions/communication/serial/">here</a>.</p>
<h3 id="heading-print-and-println-functions"><code>print()</code> and  <code>println()</code> Functions</h3>
<p>The <code>print()</code> and <code>println()</code> functions both print data to the serial monitor. The difference between the two is that <code>print()</code> prints data on the same line while <code>println()</code> prints each data on a new line.</p>
<p>Here are some examples:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  Serial.print(<span class="hljs-string">"Hello"</span>); 
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>In the code above, we used the <code>print()</code> function to print "Hello" to the serial monitor repeatedly with a delay of 1000 milliseconds. Here's what the output looks like in the serial monitor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/print.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here's another example using the <code>println()</code> function:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  Serial.println(<span class="hljs-string">"Hi"</span>);
  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>Here's the output in the serial monitor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/println.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-receive-data-with-serial-monitor">How to Receive Data with Serial Monitor</h2>
<p>We'll discuss four functions in this section — <code>available()</code>, <code>readString()</code>, <code>parseInt()</code>, and <code>parseFloat()</code>. You can read up on other serial functions <a target="_blank" href="https://www.arduino.cc/reference/en/language/functions/communication/serial/">here</a>.</p>
<h3 id="heading-available-function"><code>available()</code> Function</h3>
<p>The <code>Serial.available()</code> function checks the number of characters in the serial port. It is mostly use to run code only when data is available in the serial monitor.</p>
<p>Here's a code example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {
    userInput = Serial.parseInt();

    Serial.println(userInput);
  }

}
</code></pre>
<p>In the code above, the code block in the <code>if</code> statement will not run until the number of characters in the serial monitor is greater than 0.</p>
<p>When you initialize the serial monitor, the number of readable characters will be zero because there is no data available yet. The <code>Serial.available()</code> function checks and returns the number of characters available in the serial monitor. So it is used to create logic that only lets code be executed when data is available.</p>
<h3 id="heading-readstring-function"><code>readString()</code> Function</h3>
<p>You can use the <code>readString()</code> function to read characters from the serial monitor. It returns a string object so whatever values/characters you input in the serial monitor will be seen as string values when using the <code>readString()</code> function.</p>
<pre><code class="lang-cpp">String userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {
    userInput = Serial.readString();

    Serial.println(userInput);
  }

}
</code></pre>
<h3 id="heading-parseint-function"><code>parseInt()</code> Function</h3>
<p>The <code>parseInt()</code> function returns valid integer values from incoming serial data. Non integer values will be returned as 0.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {
    userInput = Serial.parseInt();

    Serial.println(userInput);
  }

}
</code></pre>
<h3 id="heading-parsefloat-function"><code>parseFloat()</code> Function</h3>
<p>The <code>parseFloat()</code> function returns valid floating point numbers from incoming serial data.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">float</span> userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  Serial.begin(<span class="hljs-number">9600</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{
  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {
    userInput = Serial.parseFloat();

    Serial.println(userInput);
  }

}
</code></pre>
<h2 id="heading-serial-monitor-project">Serial Monitor Project</h2>
<p>In this section, you'll build a project that uses string values from the serial monitor to turn on LEDs. We'll make use of some of the serial functions discussed in previous sections.</p>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/serial-communication-project.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the circuit diagram above, we have three LEDs. The red LED is connected to pin 6, the blue LED to pin 5, and the yellow LED to pin 4.</p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> redLED = <span class="hljs-number">6</span>;
<span class="hljs-keyword">int</span> blueLED = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> yellowLED = <span class="hljs-number">4</span>;

String userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span></span>{
  pinMode(redLED, OUTPUT);
  pinMode(blueLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  Serial.begin(<span class="hljs-number">9600</span>);

  Serial.println(<span class="hljs-string">"Choose an LED to turn on from the list below:"</span>);
  Serial.println(<span class="hljs-string">"red"</span>);
  Serial.println(<span class="hljs-string">"blue"</span>);
  Serial.println(<span class="hljs-string">"yellow"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span></span>{

  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {

    userInput = Serial.readString();

    <span class="hljs-keyword">if</span> (userInput == <span class="hljs-string">"red"</span>) {
      digitalWrite(redLED, HIGH);
      digitalWrite(blueLED, LOW);
      digitalWrite(yellowLED, LOW);
    } 

    <span class="hljs-keyword">if</span> (userInput == <span class="hljs-string">"blue"</span>) {
      digitalWrite(redLED, LOW);
      digitalWrite(blueLED, HIGH);
      digitalWrite(yellowLED, LOW);
    }

    <span class="hljs-keyword">if</span> (userInput == <span class="hljs-string">"yellow"</span>) {
      digitalWrite(redLED, LOW);
      digitalWrite(blueLED, LOW);
      digitalWrite(yellowLED, HIGH);
    }

  }

}
</code></pre>
<p>Let's break down the code above.</p>
<p>Just like the connection in the circuit diagram, we initialized the three LEDs with their respective pin numbers. We also created a string variable called <code>userInput</code> that will be used to store the data from the serial monitor:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> redLED = <span class="hljs-number">6</span>;
<span class="hljs-keyword">int</span> blueLED = <span class="hljs-number">5</span>;
<span class="hljs-keyword">int</span> yellowLED = <span class="hljs-number">4</span>;
</code></pre>
<p>We then configured the three LEDs as output pins using the <code>pinMode()</code> function:</p>
<pre><code class="lang-cpp">pinMode(redLED, OUTPUT);
pinMode(blueLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
</code></pre>
<p>We initialized the serial monitor with a baud rate of 9600, and printed some strings to give users a hint at the expected values to be used in the serial monitor:</p>
<pre><code class="lang-cpp">Serial.begin(<span class="hljs-number">9600</span>);

Serial.println(<span class="hljs-string">"Choose an LED to turn on from the list below:"</span>);
Serial.println(<span class="hljs-string">"red"</span>);
Serial.println(<span class="hljs-string">"blue"</span>);
Serial.println(<span class="hljs-string">"yellow"</span>);
</code></pre>
<p>At this point, you'll have an output like this in the serial monitor:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/project-output.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Using the <code>Serial.available()</code> function, we check for availability of serial data before running the code in the <code>if</code> statement:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {
    ...
}
</code></pre>
<p>The next thing we did was to read and return the incoming data as string values, and store the data in the <code>userInput</code> variable. We did that using the <code>readString()</code> function:</p>
<pre><code class="lang-cpp">userInput = Serial.readString();
</code></pre>
<p>Lastly, we used <code>if</code> statements to check which LED color value the user has typed in/sent through the serial monitor, then turn on/off the respective LEDs:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">if</span> (userInput == <span class="hljs-string">"red"</span>) {
  digitalWrite(redLED, HIGH);
  digitalWrite(blueLED, LOW);
  digitalWrite(yellowLED, LOW);
} 

<span class="hljs-keyword">if</span> (userInput == <span class="hljs-string">"blue"</span>) {
  digitalWrite(redLED, LOW);
  digitalWrite(blueLED, HIGH);
  digitalWrite(yellowLED, LOW);
}

<span class="hljs-keyword">if</span> (userInput == <span class="hljs-string">"yellow"</span>) {
  digitalWrite(redLED, LOW);
  digitalWrite(blueLED, LOW);
  digitalWrite(yellowLED, HIGH);
}
</code></pre>
<p>If you type and send red through the serial monitor, the red LED comes on while the others goes off. The same logic applies to sending blue or yellow through the serial monitor.</p>
<h1 id="heading-chapter-7-how-to-use-displays-in-arduino">Chapter 7: How to Use Displays in Arduino</h1>
<p>You can use display components in Arduino to represent data visually in different formats like text, images, and so on.</p>
<p>Displays provide an alternative to showing data other than the serial monitor. You can use them to display sensor values, instructions to users, user input, and so on.</p>
<p>There are various types of display components when it comes to building with Arduino but we'll focus on the LCD (Liquid Crystal Display).</p>
<p>To be more specific, we'll use the 16 x 2 LCD (HD44780). This is what it looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/lcd-component.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From the image above, there are sixteen pins with different values. We'll use most of these pins to make connections to the Uno board which will enable us use and control the component.</p>
<p>There are generally two ways of connecting the LCD — using the built-in library or using a third-party library.</p>
<p>With the built-in <code>LiquidCrystal</code> library, you'll make use of about 12 pins on the LCD component. When it comes to using a third-party library like <code>LiquidCrystal_I2C</code>, you'll make use of just 2 pins.</p>
<p>We'll be using the first method — this will help you understand how the pins work. Now let's talk about those pins.</p>
<h2 id="heading-what-are-the-pins-in-an-lcd-used-for">What are the pins in an LCD used for?</h2>
<p>The pins control functionalities like memory management, data transfer, and power on an LCD. Let's talk about them in detail:</p>
<ul>
<li>The first pin from the left is the GND pin, which is the LCD's ground pin. It is connected to GND on the Arduino board. In some LCD modules, it may be written as VSS.</li>
<li>The VCC is the power pin which is connected to 5V on the Arduino board. In some LCD modules, it may be written as VDD.</li>
<li>The V0 pin is used to adjust the contrast of the LCD. It is connected to a potentiometer. Tuning the potentiometer changes the contrast of the data being displayed.</li>
<li>The RS (Register Select) pin can be used to control the LCD's memory. It is usually connected to a digital pin.</li>
<li>The RW (Read/Write) pin controls whether data is written or read to the LCD. It is usually connected to ground (GND) which sets the LCD to write mode — this enables you to send and display data with the LCD.</li>
<li>The E (Enable) pin "enables" data transfer between the microcontroller (in our case, the Uno board) and the LCD. It is usually connected to a digital pin.</li>
<li>The D0 to D7 (can also be written as DB0 to DB7) are the data pins. There are used to send data to the LCD in bits. In most cases, the D4 to D7 pins are used. The main difference is that data is sent in 4-bits with the D0 to D3 pins, while data is sent in 8-bits with the D4 to D7 pins. There are usually connected to digital pins.</li>
<li>The LED pins are used to control the backlight of the LCD. In some LCD modules, they may be written as BLA and BLK, or A and K. The first LED pin is connected to 5V using a resistor while the second LED pin is connected to ground (GND).</li>
</ul>
<h2 id="heading-example-1-how-to-connect-and-use-an-lcd-with-arduino">Example #1 – How to Connect and Use an LCD with Arduino</h2>
<p>In the last section, we talked about the meaning of the pins on an LCD. In this section, you'll see a practical example on how to connect them in a circuit, and write code to display data on the LCD.</p>
<p>We'll use the following components:</p>
<ul>
<li>Arduino Uno.</li>
<li>16 x 2 LCD.</li>
<li>Potentiometer.</li>
<li>Jumper wires.</li>
<li>Resistors.</li>
<li>Breadboard.</li>
</ul>
<p>Here's what the circuit diagram looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/lcd.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the circuit above, we made the following connections from the LCD to the Uno board:</p>
<ul>
<li>The LCD's GND pin was connected to GND on the Uno board.</li>
<li>The LCD's VCC pin was connected to 5V on the Uno board.</li>
<li>The V0 pin was connected to the potentiometer.</li>
<li>The RS pin was connected to digital pin 4 on the Uno board.</li>
<li>The RW pin was connected to GND on the Uno board.</li>
<li>The LCD's D4 was connected to digital pin 6 on the Uno board.</li>
<li>The LCD's D5 was connected to digital pin 7 on the Uno board.</li>
<li>The LCD's D6 was connected to digital pin 8 on the Uno board.</li>
<li>The LCD's D7 was connected to digital pin 9 on the Uno board.</li>
<li>The first LED pin was connected to 5V.</li>
<li>The second LED pin was connected to GND.</li>
</ul>
<p>For the potentiometer, one of the outer legs (either the left or right) was connected to 5V, the other outer leg was connected to GND. Then the middle leg of the potentiometer was connected to the V0 pin on the LCD. This will enable you to control the contrast of the LCD.</p>
<p>Next, we'll write some code!</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal.h&gt;</span></span>

<span class="hljs-function">LiquidCrystal <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  lcd.begin(<span class="hljs-number">16</span>, <span class="hljs-number">2</span>);
  lcd.print(<span class="hljs-string">"freeCodeCamp!"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{

}
</code></pre>
<p>In the code above, we first included/imported the built-in <code>LiquidCrystal</code> library which can be used to interact with an LCD using Arduino code: <code>#include &lt;LiquidCrystal.h&gt;</code>.</p>
<p>We then initialized the <code>lcd</code> object with the required pin numbers: <code>LiquidCrystal lcd(4, 5, 6, 7, 8, 9)</code>. The first number denotes the RS pin. The second number denotes the E pin. The last four numbers denote the data pins (D4 to D7).</p>
<p>Next, we initialized the number of columns and rows using the <code>lcd.begin()</code> function: <code>lcd.begin(16, 2)</code>. We have 16 columns and 2 rows.</p>
<p>The <code>lcd.print</code> function prints data to the LCD. If you've made all the connections right, you should see "freeCodeCamp" displayed on the LCD.</p>
<p>In the next examples, we'll work with user input and sensor data, and also see other <code>lcd</code> functions.</p>
<h2 id="heading-example-2-how-to-display-user-input-with-lcd-in-arduino">Example #2 – How to Display User Input with LCD in Arduino</h2>
<p>In this example, we'll accept input from the user using the serial monitor, and display the input along with a welcome message on the LCD screen.</p>
<p>We'll make use of the same circuit in the previous example. Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal.h&gt;</span></span>
<span class="hljs-function">LiquidCrystal <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>)</span></span>;

String userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  lcd.begin(<span class="hljs-number">16</span>, <span class="hljs-number">2</span>);

  lcd.print(<span class="hljs-string">"Input name"</span>);

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {

    userInput = Serial.readString();
    lcd.print(<span class="hljs-string">"Welcome "</span> + userInput);
  }
}
</code></pre>
<p>In the code above, we created a string variable called <code>userInput</code> which will be used to store the value of the user's input.</p>
<p>We then initialized the serial monitor — <code>Serial.begin(9600);</code></p>
<p>Next, we set the rows and columns of the LCD using the <code>lcd.begin</code> function.</p>
<p>Using the <code>lcd.print</code> function, we printed "Input name" on the LCD screen.</p>
<p>This was followed by the <code>lcd.setCursor(0, 1)</code> function which has two parameters — 0 and 1. 0 represents first column on the left while 1 represents the second row. So the cursor will be set to the second line of the LCD.</p>
<p>We set the cursor to be on the second line because we already have some text ("input name") on the first line so it would be more ideal in this case to print the message to the user on the next line. I'll show you an alternative way to do this after this example.</p>
<p>In the <code>void loop()</code> function, we used the <code>Serial.readString()</code> function to read the value of user's input and stored it in the <code>userInput</code> variable.</p>
<p>Lastly, we printed a welcome message and the user's name in the LCD. This will be printed on the second line because that's where we set the cursor to be.</p>
<p>Play around with the code and see what happens as you adjust the parameters of the <code>lcd.setCursor()</code> function. This will help you understand it better.</p>
<h3 id="heading-example-2-alternative">Example #2 Alternative</h3>
<p>An alternative way to print the message to the user is by using the same line where the initial message was displayed. We can clear whatever is written on the first row of the LCD and display a different value.</p>
<p>Here's how:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal.h&gt;</span></span>
<span class="hljs-function">LiquidCrystal <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>)</span></span>;

String userInput;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  Serial.begin(<span class="hljs-number">9600</span>);
  lcd.begin(<span class="hljs-number">16</span>, <span class="hljs-number">2</span>);

  lcd.print(<span class="hljs-string">"Input name"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">if</span> (Serial.available() &gt; <span class="hljs-number">0</span>) {
    lcd.clear();
    userInput = Serial.readString();
    lcd.print(<span class="hljs-string">"Welcome "</span> + userInput);
  }
}
</code></pre>
<p>In this example, we used the <code>lcd.clear()</code> function to clear the initial request message and display/print the welcome message to the user. The rest of the logic is the same.</p>
<p>So when you type in a name in the serial monitor an hit enter, the request message ("Input name") will be cleared while the welcome message will be displayed with the name you inputted.</p>
<h2 id="heading-example-3-how-to-display-sensor-data-with-lcd-in-arduino">Example #3 – How to Display Sensor Data with LCD in Arduino</h2>
<p>In this example, we'll display data from a sensor on the LCD. We'll use the temperature sensor. The logic here is to sense the temperature of a room and display the varying values on the LCD.</p>
<p>Here are the components we'll use:</p>
<ul>
<li>Arduino Uno.</li>
<li>16 x 2 LCD.</li>
<li>Light-Dependent Resistor (LDR).</li>
<li>Potentiometer.</li>
<li>Jumper wires.</li>
<li>Resistors.</li>
<li>Breadboard.</li>
</ul>
<p>Here's the circuit diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/lcd-ldr.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The circuit diagram is almost the same as the ones in the previous examples, except that we added an LDR to measure the intensity of light. Using the LDR, we'll read, store, and display the value of light intensity on the LCD.</p>
<p>Here's the code:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;LiquidCrystal.h&gt;</span></span>
<span class="hljs-function">LiquidCrystal <span class="hljs-title">lcd</span><span class="hljs-params">(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>)</span></span>;

<span class="hljs-keyword">int</span> ldrPin = A1;
<span class="hljs-keyword">int</span> ldrValue;

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
  pinMode(ldrPin, INPUT);
  lcd.begin(<span class="hljs-number">16</span>, <span class="hljs-number">2</span>);
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
  ldrValue = analogRead(ldrPin);

  lcd.clear();
  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
  lcd.print(<span class="hljs-string">"LDR value:"</span>);

  lcd.setCursor(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>);
  lcd.print(ldrValue);

  delay(<span class="hljs-number">1000</span>);
}
</code></pre>
<p>Let's break down the code.</p>
<p>We started by including the built-in <code>LiquidCrystal</code> library and initialized the respective pins for working with the LCD (refer to the first example if you do not understand how the connection and initialization works).</p>
<p>We then created two variables: <code>ldrPin</code> which denoted the analog pin connected to the LDR, and <code>ldrValue</code> to store the readings from the LDR.</p>
<p>In <code>void setup()</code>, we configured the LDR as an input pin and set the columns and rows of the LCD.</p>
<p>Next, we read the value of the LDR using the <code>analogRead</code> function and stored that value in the <code>ldrValue</code> variable.</p>
<p>Using the <code>lcd.clear()</code> function, we clear the display after each reading. This helps in making the reading appear more accurately. If you remove the function, then some values will still be on display and make your results appear inaccurately (I spent about thirty minutes figuring this out 😂).</p>
<p>After that, we set the cursor on the first row and column of the LCD: <code>lcd.setCursor(0, 0)</code>, and displayed a message ("LDR value:").</p>
<p>Using the <code>lcd.setCursor(0, 1)</code> function, we moved the cursor down to the second row, and used <code>lcd.print(ldrValue)</code> to print/display the value of the LDR on the LCD.</p>
<p>Lastly, we added a delay of 1000 milliseconds.</p>
<p>Now you can see the value of light intensity in your environment displayed on the LCD. </p>
<p>You can use a flashlight to increase and decrease the exposure of light on the LDR, and then observe the values change on the LCD. Pretty cool!</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Congratulations! We've come to the end of this handbook. You now have enough knowledge to take on bigger projects. </p>
<p>And that should be your next goal — applying these concepts to projects that aid you and the people around you. There is no limit to what you can create. You can start by watching a couple of videos to see the type of projects people build, then you can come up with yours.</p>
<p>This handbook covered the necessary parts of Arduino (both hardware and software) that you'll need as a beginner to kickstart your journey. </p>
<p>The best way to improve and retain what you've learned is by practicing and building.</p>
<p>Happy tinkering!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Create Your Own Electronics With Arduino - Full Course ]]>
                </title>
                <description>
                    <![CDATA[ Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor, turni... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-your-own-electronics-with-arduino-full-course/</link>
                <guid isPermaLink="false">66b201e325ef0bb2c5a51711</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 08 Jun 2021 21:05:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/arduino3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Arduino is an open-source electronics platform based on easy-to-use hardware and software.</p>
<p>Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board.</p>
<p>We just released a full course on the freeCodeCamp.org YouTube channel that will teach you how to use Arduino hardware and software.</p>
<p>Ashish Bansal developed this course. He will teach you everything you need to know to start creating your own electronics with Arduino. And you don't even have to have any hardware to follow along.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/Arduino-uno-perspective-transparent.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here are all the topics covered in this comprehensive course:</p>
<h3 id="heading-section-1-objective-of-the-course">Section 1: Objective of the course</h3>
<ul>
<li>Course Introduction</li>
</ul>
<h3 id="heading-section-2-foundation-of-electronics">Section 2: Foundation of Electronics</h3>
<ul>
<li>Electricity </li>
<li>Static Electricity </li>
<li>Current Electricity </li>
<li>Voltage </li>
<li>Current </li>
<li>Resistance </li>
<li>Ohm’s Law </li>
<li>Ohm’s Law Example  </li>
<li>Resistances in Series and Parallel  </li>
<li>Resistance Color Coding</li>
</ul>
<h3 id="heading-section-3-intro-to-arduino-board">Section 3: Intro to Arduino Board</h3>
<ul>
<li>What is Microcontroller and Microprocessor </li>
<li>What category Arduino falls into? </li>
<li>Different Types of Arduino Boards </li>
<li>About Arduino </li>
<li>Parts of Arduino Uno </li>
<li>Technical Specifications of Arduino Uno</li>
</ul>
<h3 id="heading-section-4-intro-to-arduino-ide">Section 4: Intro to Arduino IDE</h3>
<ul>
<li>What is IDE? </li>
<li>Downloading and Installing the official IDE </li>
<li>Preparing your computer </li>
<li>Testing the Arduino.  </li>
<li>What if you don’t have an Arduino board?</li>
</ul>
<h3 id="heading-section-5-before-we-move-ahead">Section 5: Before we move ahead</h3>
<ul>
<li>What is breadboard? </li>
<li>How to make connections in breadboard? </li>
<li>Some safety instructions and Do’s and Don’ts  </li>
<li>Input &amp; Output </li>
<li>Analog &amp; Digital </li>
<li>Bit &amp; Byte</li>
</ul>
<h3 id="heading-section-6-arduino-programming">Section 6: Arduino Programming</h3>
<ul>
<li>Introduction </li>
<li>The First Step into Programming </li>
<li>Bare minimum structure of an Arduino Program</li>
<li>Comments </li>
<li>White Spaces and Case Sensitivity </li>
<li>pinMode </li>
<li>digitalWrite and delay </li>
<li>Camel casing</li>
</ul>
<h3 id="heading-section-61-introduction-to-variables-and-data-types">Section 6.1 Introduction to Variables and Data Types</h3>
<ul>
<li>What are variables and data types  </li>
<li>Int data type </li>
<li>Arithmetic operators </li>
<li>Incrementing and Decrementing our variables </li>
<li>Float data type </li>
<li>Bool/Boolean data type </li>
<li>Byte data type </li>
<li>Char data type </li>
<li>Conclusion </li>
</ul>
<h3 id="heading-section-62-variable-scope-and-qualifiers">Section 6.2 Variable Scope and Qualifiers</h3>
<ul>
<li>What is Scope? Global and Local Variables </li>
<li>What are Qualifiers, starting with const qualifier </li>
<li>Alternative to const qualifier: #define  </li>
<li>Static Qualifier</li>
</ul>
<h3 id="heading-section-62-comparison-and-logical-operators">Section 6.2 Comparison and Logical Operators</h3>
<ul>
<li>What are comparison operators? </li>
<li>What are Logical Operators?</li>
</ul>
<h3 id="heading-section-63-control-structures">Section 6.3 Control Structures</h3>
<ul>
<li>if statement </li>
<li>else statement </li>
<li>A joke :P  </li>
<li>if - else Simulation </li>
<li>Introduction to loop control structures </li>
<li>For loop </li>
<li>While loop </li>
<li>do…while loop </li>
<li>break </li>
<li>continue </li>
<li>return </li>
<li>switch..case</li>
</ul>
<h3 id="heading-section-64-remaining-data-types">Section 6.4 Remaining data types</h3>
<ul>
<li>Arrays </li>
<li>Strings</li>
</ul>
<h3 id="heading-section-65-functions">Section 6.5 Functions</h3>
<ul>
<li>What are functions? </li>
<li>Create your own functions</li>
</ul>
<h3 id="heading-section-66-arduino-built-in-functions-and-related-concepts">Section 6.6 Arduino Built-in Functions and related concepts</h3>
<ul>
<li>digitalRead &amp; digitalWrite </li>
<li>analogRead and Analog to Digital Converter (ADC) </li>
<li>analogWrite and Pulse Width Modulation (PWM)</li>
</ul>
<h3 id="heading-section-67-libraries">Section 6.7 Libraries</h3>
<ul>
<li>What are Libraries?</li>
<li>How to add Libraries in Arduino IDE</li>
<li>What's next?</li>
</ul>
<p>Watch the full course below or on <a target="_blank" href="https://youtu.be/zJ-LqeX_fLU">the freeCodeCamp.org YouTube channel</a> (4-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/zJ-LqeX_fLU" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Improve Your Arduino Ventilators: Intro to RTSs and SCSs for Makeshift COVID-19 Ventilator Designs ]]>
                </title>
                <description>
                    <![CDATA[ By Armstrong Subero The world as we know it was recently taken by storm. That storm was the outbreak of the COVID-19 pandemic. This has in turn created a shortage of ventilators world wide which has led many people to foray into the world of ventilat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/programming-the-electronics-for-covid-19-ventilators/</link>
                <guid isPermaLink="false">66d45d9ac7632f8bfbf1e3d5</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 02 Apr 2020 08:10:52 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9bd5740569d1a4ca2e2b.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Armstrong Subero</p>
<p>The world as we know it was recently taken by storm. That storm was the outbreak of the COVID-19 pandemic. This has in turn created a shortage of ventilators world wide which has led many people to foray into the world of ventilator design. </p>
<p><strong>There is just one problem: many people are basing their designs around the Arduino platform</strong>. While this may be good for a proof of concept, you do not want to use it for actual life support unless absolutely necessary.</p>
<p>This is because platforms like the Arduino were designed as a platform to be used in a learning environment. They were not designed for the real time, safety-critical design that is required to build ventilators. </p>
<p>However, there are some workarounds you can employ to adapt the platform for use in a makeshift emergency ventilator if one isn't available. </p>
<p>In this post we will discuss real time systems and safety-critical systems. Hopefully you can use some of these principles in your own ventilator control system designs to improve their safety and reliability. </p>
<p>Since the target audience is mainly web developers trying their hand at embedded design, I will try to make this post as self contained as possible. Join me as we dive from the browser into the realm of embedded systems design and move closer to the hardware to design our ventilators. </p>
<h2 id="heading-embedded-systems"><strong>Embedded Systems</strong></h2>
<p>For all its usefulness a ventilator is simply an embedded system. An embedded system is a system that is designed to carry out one function and to perform it well, with high reliability and minimal user intervention.</p>
<p>To accomplish this an embedded system consists of two components: a hardware system as well as a software component to run the hardware configuration.</p>
<p>A classical embedded system is typically powered by a control device which generally integrates RAM, ROM, as well as a host of embedded peripherals on board to allow the system to accomplish its task. </p>
<p>Modern embedded systems can sometimes be based around an applications processor, which may integrate a GPU, multiple CPU cores, multimedia codecs and other devices. Though applications processors can be used in embedded systems, they are mainly used in general purpose computing systems such as a smartphone. </p>
<p>The software that runs on an embedded system is called firmware. It is called firmware because once written into ROM, it is not expected to change frequently. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image.png" alt="Image" width="600" height="400" loading="lazy">
<em>Components of An Embedded System</em></p>
<p>Think of a ventilator. Its main purpose is to provide mechanical ventilation to keep patients alive. It performs one function and does it with a high degree of reliability, to such an extent that it can be used as a life support system. Very rarely do you find someone changing the firmware in such a device once deployed.  </p>
<h2 id="heading-the-hardware-component">The Hardware Component</h2>
<p>As stated previously, the embedded system has a hardware component which integrates RAM, ROM and other devices in one package. This device is called a microcontroller. </p>
<p>There are several popular microcontrollers today. The PIC and AVR from Microchip Technology and the STM32 from STMicroelectronics are the most popular. The classic Arduino uses an AVR microcontroller at its core. </p>
<p>Regardless of the manufacturer, the microcontroller will consist of a processor core, memory and a means to provide input and output also known as I/O. </p>
<p>Microcontrollers also consist of memory which are divided into two categories: data memory and program memory. </p>
<p>Data memory is memory that is used to store data that will be used by the microcontroller during run time. It is typically a few tens to a few hundred kilobytes of SRAM. Data memory is volatile and is lost when power is removed from the device.</p>
<p>Program memory on the other hand, actually stores the memory that will be used by the microcontroller. It consists of Flash (think the memory in your USB flash drive) or FRAM (Ferroelectric RAM) and is not volatile. The size of program memory typically ranges from a few bytes to a couple of megabytes on modern systems. </p>
<p>The Input and Output (I/O) pins on the microcontroller are what allow the device to communicate with external devices such as sensors and other chips that perform various functions such as memory expansion and even adding additional I/O to the device. </p>
<p>A microcontroller will also integrate peripherals for performing analog to digital (A to D) and digital to analog (D to A) functionality. </p>
<p>This is because our world is analog in nature and Analog to Digital Conversion (ADC) will convert real world data into a format our microcontroller can process. If you have a voice recorder, a microphone sensor together with a microcontroller will convert your voice into a digital format and store it. </p>
<p>The microcontroller may also have means to perform Digital to Analog Conversion (DAC) whereby digital data can be converted into an analog format that we can utilize in the real world. </p>
<p>In our voice recorder example, this would be applicable when you must play back your recorded voice. The stored digital information is converted to sound we can detect in our analog world. </p>
<p>When we combine all this we get a block diagram of typical microcontroller hardware. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Crude Microcontroller Block Diagram</em></p>
<p>Now that we have a basic understanding of the hardware, let's look at the software component. </p>
<h2 id="heading-the-software-component">The Software Component</h2>
<p>As great as your hardware is, without the software to control it, it's as useful as a paper weight. Software in embedded systems typically fall into three basic categories: </p>
<ul>
<li>cyclic execution systems, </li>
<li>finite state machine based systems, and </li>
<li>systems build using a real time operating system. </li>
</ul>
<p>The difference between these three types of software systems is based on the way they handle tasks. When we speak about tasks, what we are talking about is the smallest unit of execution within your firmware. </p>
<h3 id="heading-cyclic-execution-systems">Cyclic Execution Systems</h3>
<p>A cyclic execution system works by having all the program tasks contained in an infinite loop. These systems have one main program entry point, and then the system cycles through a list of tasks. This is the simplest type of firmware design and is used for basic systems. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Cyclic Execution System</em></p>
<p>This system will have a program entry point which would typically configure hardware and set up systems clocks and basic bring up tasks. Once the program enters into the infinite loop, it will perform Task one, then Task two and finally Task three.</p>
<h3 id="heading-finite-state-machine">Finite State Machine</h3>
<p>While the cyclic based execution system is simple and effective for most tasks, sometimes you need a little more control over program flow. When this occurs a designer may use what is known as a Finite State Machine (FSM) system.</p>
<p>In a FSM, we can think of each task as a state the machine can be in. The FSM will have an initial state and after that each state will execute based on some conditional statement. The coin acceptor turnstile is usually used (like the hello world of state machines) to explain the concept of a state machine. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-3.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Coin Acceptor Turnstile FSM". (Source Codeless Data Structures and Algorithms by Armstrong Subero).</em></p>
<p>We have a black dot which represents the initial state along with two states, locked and unlocked. The turnstile in a locked state will become unlocked once you insert a coin. Even if you push on the machine it will not unlock until you insert a coin. Once you insert a coin the machine enters into the unlocked state and will remain in that state as long as a coin a present.</p>
<p>If you push on the turnstile while in the unlocked state, that condition will cause the machine to transition into a locked state which it will remain in until a coin is entered again.</p>
<p>As simple as it seems, this method of modeling program tasks as states which transition based on conditions is a powerful method of embedded system firmware design. It is the method I use most often when designing my own systems.</p>
<h2 id="heading-ventilators-are-real-time-systems">Ventilators are Real Time Systems</h2>
<p>Real Time Systems or RTS are systems which must meet strict requirements in terms of response times. In a real time system there is no room for compromise. </p>
<p>Such systems must guarantee that they will perform an action within a given time period. Failure to perform action within a certain time may lead to loss of life or serious damage to property.</p>
<p>This is the category of systems a ventilator falls into. </p>
<p>When a patient requires a ventilator, it is because they cannot breathe properly and need mechanical assistance to breathe required by a ventilator. A ventilator can perform Continuous Mandatory Ventilation (CMV) which means that the patient will be required to get a minimum number of breaths from the machine guaranteed. </p>
<p>Failure to provide the minimum number of breaths required will result in death of the patient. That means that the control electronics must be able to perform without failure. </p>
<p>To accomplish this most real time systems will utilize what is known as a real time operating system (RTOS) to ensure that the many tasks to be performed by the device can all be performed without fail.</p>
<p>RTOSs use a scheduler to manage tasks and limit how each task utilizes resources. The kernel would manage how each task can utilize the hardware resources based on their priority.</p>
<p>Think of the current makeshift ventilator designs that exist. The most promising ones are built using a bag-valve resuscitator that uses motors to actuate mechanical arms that press on the bag-value resuscitator and perform the ventilator functions. </p>
<p>However what will happen if the motor fails? Maybe we can add an infrared or ultrasonic sensor that will measure distance of the the mechanical arm from a certain point and ensure it reaches a particular distance. These sensors can also ensure that it returns to the starting point. </p>
<p>However the main microcontroller reading those sensors needs time to process the information. What if a sensor fails? Must the microcontroller lock up waiting for sensor data? Will a failure in sensor prevent the motor from being actuated on time?</p>
<p>To ensure each task takes place at a certain time, the scheduler will only allocate processing time to the task as designated by the system designer. </p>
<p>That way if a sensor fails, once the time allocated to reading that sensor has passed, the microcontroller will move on to the other task of actuating the motor which will keep the system running. </p>
<p>Using a Real Time Operating System in your design will guarantee that your device will be able to perform its function within the specified time. </p>
<h2 id="heading-ventilators-are-safety-critical-systems">Ventilators are Safety Critical Systems</h2>
<p>In the previous section we discussed real time operating systems. I think we should expand our discussion a little and talk about hard real time vs soft real time systems. </p>
<p>In hard real time systems, the requirement of operation is that it MUST happen within the specified time at all costs, and failure to meet deadlines is not acceptable. Air traffic control systems and ventilator systems fall into this category. </p>
<p>Hard real time systems are not allowed to miss deadlines.</p>
<p>In soft real time systems, it is preferred that deadlines are met. But if deadlines are not always met it means that it may upset the end user but may be acceptable. Think of an online gaming platform. We would like to have real time response of our games, but if you miss a few frames it will not result in loss of life.</p>
<p>Soft real time systems are allowed to miss deadlines.</p>
<p>Now, a lot of people mistake a real time system with a safety critical system. Not all real time systems are safety critical systems. Think of the example above with online gaming or video conferencing – such systems require real time performance but they are not safety critical in nature.</p>
<p>What makes a safety critical system (SCS) different from a regular real time system is that failure to meet a deadline within a safety critical system will result in death or serious property loss.</p>
<p>In a safety critical system, stoppage of the system is NOT an option.</p>
<p>For example a high availability system real time system may be specified as having an up time of around 99% in a 24 hour period. </p>
<p>Think about a ventilator system. </p>
<p>Which 1% of the day is it acceptable to have the ventilator not operational? Since we have 1440 minutes in a day, which 14.4 minutes of the day should the patient not be allowed to breathe?</p>
<h2 id="heading-the-arduino-platform">The Arduino Platform</h2>
<p>At this stage in our discussion, I think it's best we talk about the Arduino platform for use in safety critical systems.</p>
<p>In our discussion of embedded systems, we talked about hardware and software, however did you know that there is also the development tools component of the design process?</p>
<p>You see, in order to put the software you have written into the microcontroller device running the hardware, you need to use development tools such as an IDE and toolchain to program the device.</p>
<p>Setting up and using a toolchain was a painful process depending on the device you were using. Many microcontroller vendors used to provide clunky IDEs that you had to be a seasoned embedded designer to use (though this has changed in recent years).</p>
<p>Additionally you also needed knowledge of the underlying hardware, and configuring registers and clocks can be daunting even for experienced designers. </p>
<p>Even if you overcame these hurdles on the software side, you needed to have a Printed Circuit Board (PCB) or have experience using a breadboard to get your microcontroller running. </p>
<p>It you did not know how to properly connect your hardware, even if your program was correct, the device would not run and troubleshooting the hardware also required some experience. </p>
<p>In order to address the problem, the Arduino platform was introduced as a way to provide synergy between hardware, software, and development tools to allow students control hardware with ease. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/image-4.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Components of the Arduino Platform</em></p>
<p>The Arduino provides a physical board with the chip that is in a configuration known to work along with a simple IDE with tons of libraries. This seamless integration makes a less intimidating foray for beginners looking to get into the realm of hardware design. </p>
<h2 id="heading-the-problem-with-using-arduino-in-safety-critical-systems">The Problem with Using Arduino in Safety Critical Systems</h2>
<p>There is one problem: since the Arduino is so easy to use, this has led many people to use the Arduino far beyond what the platform was originally intended for, including use in real time systems.</p>
<p>It's not recommended to use the Arduino for real time systems. Why? Some people may argue that you can use an operating system such as Amazon FreeRTOS on the Arduino and make it real time. That is true. But while the platform does become real time and it will make it highly reliable, it will not make it a safety critical one. </p>
<p>What makes the Arduino not suitable for use in safety critical systems? The answer lies in abstraction and its relation to the testing and debugging capability of the platform.</p>
<p>The Arduino is a good platform for learning, and as such it adds a lot of software abstraction to make things easy. </p>
<p>Abstraction in itself is not necessarily a bad thing. Abstraction allows for code reuse and can help eliminate bugs if used correctly. Properly tested code that abstracts away a lot of the hardware can be a powerful tool in the right hands.</p>
<p>However abstraction does NOT eliminate bugs and there is the problem. Even if code is abstract, if it had faulty logic to begin with then abstraction will not save you. </p>
<p>If you find a bug, usually you would rely on a debugger and software tests to help you figure out the source and improve the system reliability. </p>
<p>Therein lies the problem. The Arduino platform has no debugging capability. </p>
<p>Having no debugging makes bugs difficult to track. Having software that a bug free is crucial in a safety critical design. Additionally running tests on your code is not easy as the IDE is too simple for the powerful debugging and testing that is required for safety critical system design. </p>
<p>If you have no choice you can use the Arduino for design of a ventilator system. But the lack of debugging makes it difficult to do so and increases the likelihood of bugs in your firmware, and increases the risk of failure within the system. </p>
<h2 id="heading-how-can-i-design-a-good-makeshift-system">How Can I Design a Good Makeshift System?</h2>
<p>If you must design a ventilator system, there are two specific things you can do to improve your design based on the Arduino: You can improve the software design and improve the hardware design.</p>
<h3 id="heading-improving-design-on-the-software-side">Improving Design on the Software Side</h3>
<p>All hope is not lost. To make sure your system has reliable software consider doing the following:</p>
<ol>
<li>Consider using Another IDE - Atmel Studio is a great IDE that provides the option for debugging if you use an external debugger such as the Atmel ICE or ICD 4 debugger. Additionally MPLAB X can be used. These IDE's will assist with debugging.</li>
<li>Adhere to a C/C++ coding standard - Using a code standard can improve your system reliability and make your system design more efficient. Consider rewriting the libraries you are using to adhere to MISRA, JSF++ or even the Barr Group's embedded C coding standard</li>
<li>Use an RTOS - Many of the ventilator designs based on the Arduino utilize the platform as is with a cyclic execution system in place. Consider using the Amazon FreeRTOS to make your system real time. This would avoid system lockup and make your system more reliable.</li>
<li>Consider using a Platform with Libraries that meet Safety Requirements – While not ideal for inexperienced designers, using a device that has libraries that already have existing safety requirements will help make your design more robust.<br>For example even though our device is a makeshift medical device, using IEC 60730 requirements for Class B safety can help make your design more robust. Microchip Technology (company that makes the chip that powers the Arduino) has other devices that has libraries that meet Class B safety requirements and would aid in improving device safety. </li>
<li>Implement Sensor Data Analytic Redundancy - When designing your device consider using sensors to ensure the device is still operational and when you do, consider using analytic redundancy methods to aid with more accurate sensor data. </li>
<li>Consider using SAFERTOS - While it may require you to change systems SAFERTOS is pre-certified for use in medical systems and will provide a higher level of safety that the software of the Arduino platform. </li>
</ol>
<h3 id="heading-improving-design-on-the-hardware-side">Improving Design on the Hardware Side</h3>
<p>To improve your design on the hardware side:</p>
<ol>
<li>Consider using a Watch Dog Timer - If you don't have time to use an RTOS, a simple way to ensure your device keeps operating is to use a watchdog timer in your design. The watchdog timer ensures the device resets if a problem occurs in the execution of your code. </li>
<li>Use a Hardware Device with Pre-existing Safety Certifications and Libraries - Some devices are better suited for the task of a ventilator design. Rather than entrust a safety critical design to an Arduino, consider using a control device that can use software that is already certified for medical device use or provides safety libraries.<br>The SAFERTOS supported platforms is a good place to start. The Microchip Technology web page on Class B safety software is also a good place to start. </li>
<li>Add Feedback Systems - It is not enough to have your device up and running. You also need feedback systems to ensure devices are operating as they should. Integrate sensors to provide feedback on mechanical parts that are subject to failure. </li>
<li>Consider Distributed Hardware Control- Though many persons base their designs on a single chip consider using multiple microcontrollers in your design. Consider having one device for control and another for notifying the end user if a component is failing. </li>
<li>Implement System Redundancy - Having a proper shutdown system with a proper transfer system is crucial for such designs. Implement a proper shutdown procedure in case the system fails as well as have a proper switch over mechanism to ensure you have a 100% up time on your system. </li>
</ol>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this post we looked at embedded systems, briefly talked about their hardware and software components, and touched on firmware design paradigms. We also talked about real time systems and safety critical systems as it relates to ventilator design. </p>
<p>Finally, we talked about how to improve the safety and reliably of your Arduino-based ventilator designs by improving the hardware and software design. </p>
<p>By the end of this post you should have some understanding of how to enhance your makeshift Arduino ventilator system. </p>
<p>If you wish to learn more about microcontrollers, pick up my book "Programming PIC Microcontrollers with XC8" where you will learn about the PIC microcontroller and how to program it. This microcontroller can also be used to design your ventilators and will give you a greater degree of control and debugging capability than the Arduino platform.</p>
<p>Read the book here:</p>
<p><a target="_blank" href="https://www.apress.com/gp/book/9781484232729">https://www.apress.com/gp/book/9781484232729</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Internet of Things prototyping with Firebase: how to do more with less ]]>
                </title>
                <description>
                    <![CDATA[ By Bayrem Gharssellaoui IoT is all about connecting devices, or “things” as you may call them, to the internet and then analyzing data collected from these devices in order to extract an added value. In this article you’ll discover how to benefit fro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/iot-prototyping-with-firebase-doing-more-with-less-2f5c746dac8b/</link>
                <guid isPermaLink="false">66c35874c7095d76345eaf9e</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firebase ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Internet of Things ]]>
                    </category>
                
                    <category>
                        <![CDATA[ iot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ platformio ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 19 Jan 2019 13:23:15 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*ttEuxmPhOI8obezR7bn6tg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bayrem Gharssellaoui</p>
<p>IoT is all about connecting devices, or “things” as you may call them, to the internet and then analyzing data collected from these devices in order to extract an added value. In this article you’ll discover how to benefit from <a target="_blank" href="https://firebase.google.com/">Firebase</a> when working on an IoT project and how it can help you develop IoT prototypes much faster and easier than traditional methods. You will also develop your own IoT project and host it in Firebase.</p>
<h3 id="heading-before-firebase-realtime-database">Before Firebase Realtime Database</h3>
<p>Most of <a target="_blank" href="http://kaizoku.azurewebsites.net/">my IoT projects</a> require some way of communication between the different endpoints. These endpoints can be anything from devices and services to applications, and eventually data needs to be stored somewhere for further processing and analyzing.</p>
<p>So let’s say you want to build an IoT system where a device will measure temperature and humidity values from sensors and send them to a database service to store them. Then you want to have a web application that will fetch these values and display them in a dashboard. Quite simple, right…?</p>
<p>The easy and lightweight way to go about this is to setup an <a target="_blank" href="https://www.hivemq.com/mqtt-essentials/">MQTT</a> broker that will act as a hub and reroute all incoming messages <strong>published</strong> from the device to all <strong>subscribed</strong> clients like the web application in this case.</p>
<p>Now the question here is how can the web application display the data? Meaning will it be displaying messages coming from the broker directly or will it be fetching data from a database service?</p>
<p>Let’s say that you want the app to do both things: display data coming from the broker in realtime <strong>and</strong> fetch data from the database. In this case you can think of 2 ways (actually there are many different ways) to achieve this:</p>
<p><strong>First solution:</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*5NM__yb36ftzOmIvLtBc-A.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Using this architecture the device will first publish its data to the broker then it will send an HTTP request to the database web-service to save the data. For this solution the device needs to implement 2 clients: an MQTT and an HTTP client.</p>
<p><strong>Second solution:</strong></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*qOsO6-Hupd-Eidwdw66X-Q.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The other way to go about this is that the device will send or publish its data to the broker, then the broker (as expected) will reroute this message to all connected subscribers like the web app. But this time there’s another subscriber connected which represents an API Engine that will accept this data and send it to the database web-service to be stored.</p>
<p>As you may have noticed in this solution, the HTTP client is decoupled from the device and implemented as a backend service. This way you make the device program much lighter. This is an important thing to keep in mind when developing on constrained IoT devices where resources like CPU and memory are limited.</p>
<p>Still, this solution required some additional work in developing the back-end service that will act as a persistence layer.</p>
<p>So is there much easier way of doing this?</p>
<h3 id="heading-firebase-to-the-rescue">Firebase to the rescue</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*dFAUA_U6XtcCVDSDrd1eIQ.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you may have seen above, things can get quite complex quite easily. For someone like me who wants to get up and running quickly when working on a prototype, that can take some extra time. That’s why, in this part of the article, you’ll see how Firebase can make your life easier and save you a lot of time when developing an IoT prototype.</p>
<p>Firebase offers many cloud services that ranges from authentication, storage, and cloud functions to hosting your web application. In this article you’ll use 2 services: Realtime Database and Hosting.</p>
<p>Let’s start with <strong>Firebase Realtime Database</strong>. The first thing that comes to mind when reading this service name is: okay so I know what a database is but what does it mean to be realtime here?</p>
<p>Well according to Wikipedia:</p>
<blockquote>
<p>A <strong>real-time database</strong> is a database system which uses <a target="_blank" href="https://en.wikipedia.org/wiki/Real-time_computing">real-time processing</a> to handle workloads whose state is constantly changing. This differs from traditional databases containing persistent data, mostly unaffected by time</p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*uWzVNx2DCXbVc0xnxbSYwg.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the case of Firebase Realtime Database, clients will be connected to the database and will maintain an open bidirectional connection via <a target="_blank" href="https://blog.teamtreehouse.com/an-introduction-to-websockets">websockets</a>. Then if any client pushes data to the database it will be triggered and (in this case) inform all connected clients that it has been changed by sending them the newly saved data.</p>
<p>This way of working may remind you of the MQTT broker and how it reacts when it receives a message from a publisher and sends it to all subscribers. The difference this time is the addition of the data persistent part, which is the database. So as you can see here, you don’t need to route messages yourself using other protocols — Firebase Realtime Database will take care of that plus performing its normal database function. Amazing isn’t it?</p>
<p>Returning to the IoT system mentioned earlier, you can now connect the device to the Firebase Realtime Database and make it push data periodically to the database. On the other part of the system you have a web application which will be connected to the same service as the device and will receive new data whenever there is a change in the database.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*zyS---O8Po4Gz1tVUYS4QQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But what about <strong>hosting</strong> the web application?</p>
<p>Firebase offers a hosting service that you can use to host your app rather than managing your own web server and dealing with deployment and networking configurations. The good thing is that it is free (yet limited) and pretty easy to use.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*VESaHfq7jgk8aeDyH2kFgg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now for the part you all have been waiting for. In this demo you’ll use the example discussed throughout this article and bring it to life.</p>
<p>If you remember, the IoT system is made of <strong>2 endpoints</strong>: the first one is the <strong>IoT device</strong> which is responsible for sending temperature and humidity data to the Firebase Realtime Database. This in turn will communicate with the second endpoint — the <strong>web application</strong> — that will read the data and display it on a nice dashboard.</p>
<p>I’ll break this project into <strong>3 steps</strong> so it becomes easier to follow.</p>
<h3 id="heading-1-setting-up-firebase-realtime-database">1. Setting up Firebase Realtime Database</h3>
<p>There is nothing special about this step. You just need to go to your <a target="_blank" href="https://console.firebase.google.com/">firebase console</a> and create a new project. After your project is ready, go to the database section and make sure to create a Realtime Database <strong>not a cloud Firestore Database.</strong> Select start in test mode and proceed as you’ll be using this database only for testing and prototyping and not for production solutions (so you can ignore the red warning). Now the database should be ready for use.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*E-ny9SQDLjUGOiEn1ows8w.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-2-developing-the-iot-device-application">2. Developing the IoT device application</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*ttEuxmPhOI8obezR7bn6tg.jpeg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When talking about embedded systems development, you often hear terms like low level programming, assembly, registers, memory management and so on. These terms and concepts are related to the hardware specifics you’re working with and can change from one to another.</p>
<p>That’s why, when prototyping ideas, you don’t have time to dig deep into these specifics and study them in details because you’ll be dealing at the same time with other high level languages and thus other ways of thinking about code. So instead you should have a clear overall idea about the architecture and characteristics of the device and how to use them.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*YQyb-Sopev0IYL9nRv1J-Q.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Luckily for you there is a platform that was made specially for prototyping and abstracting all the low level functionalities of hardware. Yes I’m talking about the famous <strong>Arduino</strong>.</p>
<p><a target="_blank" href="https://www.arduino.cc/"><strong>Arduino - Home</strong></a><br><a target="_blank" href="https://www.arduino.cc/">_Open-source electronic prototyping platform enabling users to create interactive electronic objects._www.arduino.cc</a></p>
<p>Note here that when I’m talking about Arduino, I’m referring to the <strong>Arduino Framework</strong> with its IDE, compilers, and libraries — not the board.</p>
<p>So you will be using Arduino to program the board, but what board you ask? Well, you need a board that is able to interface with sensors and measure physical values like temperature. It should also be able to connect to the internet in order to send this data to the database. Finally, it should be able to be programmed using the Arduino framework.</p>
<p>There are a variety of boards on the market that can achieve these tasks. Some of them are Arduino boards and others are Arduino-compatible boards.</p>
<p>In this demo you will use the famous <strong>NodeMCU,</strong> an Arduino compatible board. It’s based on the <strong>ESP8266</strong> SoC, a chipset produced by the Shanghai-based Chinese manufacturer, Espressif Systems. This board is attractive for developers, as single units can be bought for as little as $3.</p>
<h4 id="heading-our-gear">Our Gear</h4>
<p>Although the Arduino platform offers an IDE for programming and uploading code to boards, it’s not very friendly to developers as it does not provide any intelliSense features or debugging functionalities. That’s why, for most my IoT projects, I use an environment called <strong>PlatformIO.</strong></p>
<p><a target="_blank" href="https://platformio.org/"><strong>PlatformIO: An open source ecosystem for IoT development</strong></a><br><a target="_blank" href="https://platformio.org/">_Cross-platform build system and library manager. Cross-platform IDE and unified debugger. Remote unit testing and…_platformio.org</a></p>
<p>It’s an open source ecosystem for IoT development, and guess what? It supports the Arduino Framework. So you can use it to write Arduino code, compile it, and upload it to the board. Finally the cool thing about PlatformIO is that it comes as an <strong>extension</strong> that you can use inside <strong>Atom</strong> or <strong>VScode</strong> so you can use it alongside the other functionalities of your IDE (Atom or VScode). I highly recommend watching these 2 YouTube video tutorials to setup and get familiar with the environment.</p>
<p>Enough talk — let’s get started:</p>
<h4 id="heading-developing-firmware-for-nodemcu">Developing Firmware for NodeMCU</h4>
<p><a target="_blank" href="https://github.com/kaizoku-619/firebase_nodemcu"><strong>kaizoku-619/firebase_nodemcu</strong></a><br><a target="_blank" href="https://github.com/kaizoku-619/firebase_nodemcu">_Arduino Firebase Nodemcu client developed sending DHT11 data to Firebase Realtime Database …_github.com</a></p>
<p>Before diving into developing the firmware, let’s talk about the electronics setup.</p>
<p>If you remember from the example earlier, the IoT device will measure temperature and humidity values from a sensor and send them to the cloud. In this case that means the <strong>NodeMCU</strong> will read temperature and humidity values from <strong>DHT11</strong> sensor module and send them to Firebase. The <strong>DHT11</strong> module will be used here because it’s cheap and doesn’t require any additional electronic components to function.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*B6nyhGw-sarcmZgLA2etXg.png" alt="Image" width="600" height="400" loading="lazy">
<em>Wiring Diagram</em></p>
<p>As you can see from the wiring diagram above, DHT11 is connected to the board with 3 wires <strong>GND</strong>, <strong>3.3V</strong> and <strong>Data signal</strong> in the middle. Connect the data pin to one of the <strong>Dx</strong> pins on the board and you’re done with wiring.</p>
<p>Now that the wiring is done you can start coding the firmware using PlatformIO.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*DIOV2vSxZKjRO6WgP2nzjA.gif" alt="Image" width="600" height="400" loading="lazy">
<em>We’re not writing Go but I like the GIF</em></p>
<p>But before you dig into writing code directly, let’s stop for a moment and think about what the program should do.</p>
<p>So the first thing the device needs to do is to connect to the internet. To do that it needs to <strong>connect to the WiFi</strong> access point. Once online, it needs to <strong>open a connection with Firebase.</strong> After that the device will <strong>read temperature and humidity</strong> values from the sensor and finally <strong>publish the data</strong>.</p>
<p>Here is an ordered list of tasks:</p>
<p><em>(Note that the world <strong>task</strong> is used here to refer to a functionality of a bloc of code and not a task in realtime OS like FreeRTOS tasks.)</em></p>
<p><strong>1. Connect to WiFi</strong><br><strong>2. Open connection with Firebase</strong><br><strong>3. Read sensor values</strong><br><strong>3. Publish values to Firebase</strong></p>
<p>Let’s start with the first task:</p>
<ul>
<li><strong>Connect to WiFi:</strong></li>
</ul>
<p>This function begins with printing the <strong>SSID</strong> (AP name) and setting the NodeMCU into station mode rather than AP mode. Then it keeps loading until it connects to the AP. SSID and <strong>PASSWORD</strong> are 2 constants defined in another file as you’ll see later.</p>
<ul>
<li><strong>Open connection with Firebase:</strong></li>
</ul>
<p>This function is very straightforward: it takes 2 parameters <strong>FIREBASE_HOST</strong> and <strong>FIREBASE_AUTH.</strong> These are also 2 constants defined in another file.</p>
<ul>
<li><strong>Read sensor values:</strong></li>
</ul>
<p>You start by defining 2 constants for the <strong>DHT</strong> sensor type and pin. After that you create a DHT object by passing these 2 constants to the DHT constructor. Finally you use the object methods <strong>readHumidity()</strong> and <strong>readTemperature()</strong> to read humidity and temperature respectively.</p>
<ul>
<li><strong>Publish values to Firebase:</strong></li>
</ul>
<p>Here, the <strong>pushInt()</strong> method of Firebase class is used to push an integer to Firebase and in case of an error, print it.</p>
<p>And now you’re done with the tasks! All that’s left is to put these tasks together in a clean arduino sketch.</p>
<p>Start by creating a new project in PlatformIO as shown here:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*xwXxvU1FbJBSS6yypAiKHA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next you need to <strong>install the libraries</strong> needed for the project. Note that in this case you will install the libraries <strong>locally,</strong> meaning they’re only available for this project. This is a best practice if you decided one day to use another version of the library in another project.</p>
<p>Go to the PlatformIO home page → Libraries and search for firebase. FirebaseArduino will show up, so click on it. But <strong>don’t click install button</strong>, instead click on the <strong>…</strong> next to install and choose the project to install the library into. Then finally click install. Repeat this process for the <strong>DHT</strong> library.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*gyXxo1VKPLWcqfHlkV_oLQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Copy this code in the <strong>main.cpp</strong> file:</p>
<p>Remember the file containing the credentials for the WiFi and Firebase? Go to the include folder and create a new file <strong>Creds.h</strong> and copy this code to it. Don’t forget to <strong>change</strong> the code according to <strong>your credentials</strong>.</p>
<p>And there you go! Upload the firmware to <strong>NodeMCU</strong> and your device should be able to send data to <strong>Firebase Realtime Database</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Dx4qV5dLbGQoNYcwYifa5w.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-3-developing-and-hosting-the-web-application">3. Developing and hosting the web application</h3>
<p><a target="_blank" href="https://github.com/kaizoku-619/firebase_iot_web"><strong>kaizoku-619/firebase_iot_web</strong></a><br><a target="_blank" href="https://github.com/kaizoku-619/firebase_iot_web">_Firebase web application client connected to Firebase Realtime database fetching sensor values …_github.com</a></p>
<p>Now that the IoT device is ready and pushing data to the Realtime Database, you can move to the other endpoint in the system, the web application. It will receive data from Firebase and display it on a dashboard.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*Rjf3-ZGcqjg_TUPOPmllOw.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You will start by developing the app locally and eventually deploying it.</p>
<p>Start by setting up the project.</p>
<h4 id="heading-installing-firebase-cli"><strong>Installing Firebase CLI:</strong></h4>
<p>The <strong>Firebase CLI</strong> (command line interface) requires <strong>Node.js</strong> and <strong>npm</strong> (the Node Package Manager). Once they are installed you proceed to install the Firebase CLI using npm by running:</p>
<pre><code>npm install -g firebase-tools
</code></pre><p>You can follow the video to complete the project setup.</p>
<p>Once project setup is done your directory should look something like this:</p>
<pre><code>├── database.rules.json├── firebase.json└── public   ├── <span class="hljs-number">404.</span>html   └── index.html
</code></pre><p>Start by building the <strong>dashboard UI.</strong> This will be the <strong>index.html</strong> file. Open the file and change it to look like this:</p>
<p>This is a simple <strong>HTML</strong> page designed using <a target="_blank" href="https://fezvrasta.github.io/bootstrap-material-design/">Bootstrap Material Design</a>. It consists of <strong>2 Card</strong> elements, one for displaying Humidity and the other for displaying Temperature.</p>
<p>As for the Firebase part here, first you import the firebase dependency in the script tag inside the head tag. Finally when the page finishes loading, it calls <strong>app.js</strong>.</p>
<p>Now that the Dashboard UI is ready you can move on to <strong>app.js</strong> where you implement the firebase connection and your business logic. In the same directory create a new file called <strong>app.js</strong> and copy this code:</p>
<p>The script starts by creating a configuration object. The best way is to copy it directly from the firebase project in the firebase console. To do that, navigate to your firebase console and go to the firebase project settings. Then scroll down and click on the <strong>&lt;</strong>;/&gt; icon as shown here:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*UOd3xtXrWw291dCIP2I1zw.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I guess the rest of the code is self explanatory with the comments.</p>
<p>Now your app should be ready and you can test it locally with the following command:</p>
<pre><code>firebase serve
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*ZGnT6vNho7_lNuQNvcokBw.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that on startup the app will fetch the last temperature and humidity values from the database. Great! The app is working locally, but up until now it’s working only inside your localhost and can’t be accessed from the outside world. This means that it’s time to host it on the web using <strong>Firebase Hosting.</strong></p>
<p>But before you deploy it there is just one last thing you need to do. Go to the <strong>database.rules.json</strong> file and change the read and write rules to “<strong>true</strong>”. This method is not advised for production, as it is not secure, but it’s fine for demonstration purposes here.</p>
<p>With that done you are ready for deployment:</p>
<pre><code>firebase deploy
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*RUWH_VUFf_EJ2JVeUk6xWA.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There you go! If you’ve made it this far, by now you should have a live web application deployed and up and running.</p>
<h3 id="heading-putting-it-all-together">Putting it all together</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*NRl95CtTxUi8Os7D_WKgAA.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It’s time to put everything together and test the system. Plug in the <strong>NodeMCU</strong> to your PC and upload the sketch if you haven’t already:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*neyIQF00mBE02W9aOw4ptg.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Open up the web app and the firebase database and watch it change in realtime with the values sent by the device.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*1JIi7SbvkC6LAePZiuRtjA.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now open up the <strong>serial monitor</strong> and watch the data pushed from the device to the web app. Note that you can open the console in the browser to watch the received values. Here I use <a target="_blank" href="https://linux.die.net/man/1/gtkterm">Gtk Serial port terminal</a> with a baud-rate of 115200 bps, but you can use the integrated <strong>PlatformIO</strong> Serial Monitor or any other tool of your choice.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*oPKH60n5_9kQfIIdtx_Hjg.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-troubleshooting">Troubleshooting</h3>
<p>I faced a problem while developing the application on the <strong>ESP8266</strong> (and it took me sometime to figure out). Even when everything was configured correctly (WiFi Connection, Firebase Host, Secret Key), the ESP8266 <strong>couldn’t connect to Firebase.</strong> This was caused by the <strong>wrong Fingerprint</strong> inside <strong>FirebaseHttpClient.h</strong> file in the Firebase library. You need to replace it with your own fingerprint. If you installed the library locally using <strong>PlatformIO</strong> then you can find the file in this path:</p>
<pre><code>your_project_folder/.piolibdeps/FirebaseArduino_ID1259/src/
</code></pre><p>To <strong>generate</strong> a fingerprint, go to this website and copy your Firebase host link without the https part and click on Fingerprint Site (mine is:<br>medium-iot-project.firebaseio.com):</p>
<p><a target="_blank" href="https://www.grc.com/fingerprints.htm"><strong>GRC | SSL TLS HTTPS Web Server Certificate Fingerprints</strong></a><br><a target="_blank" href="https://www.grc.com/fingerprints.htm">_GRC's HTTPS Web Server Certificate Fingerprint Service_www.grc.com</a></p>
<p>This will generate a fingerprint for your site, so go ahead and copy it in place of the old <strong>kFirebaseFingerprint[]</strong> value inside the <strong>FirebaseHttpClient.h</strong> file. That should fix the problem.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*TuJignt5v3mYTnybtktJnw.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*HC62qJvM12Ey_u_CKA3uNQ.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Congratulations if you’ve made it this far!</p>
<p>We’ve only scratched the surface here. The Internet of Things is all about experimenting and exploring, so I encourage you to not stop here and keep learning by making mistakes and finding bugs in your code. But above all don’t forget to have fun along your learning journey.</p>
<h3 id="heading-references">References</h3>
<p><a target="_blank" href="https://firebase.google.com/docs/database/"><strong>Firebase Realtime Database | Firebase Realtime Database | Firebase</strong></a><br><a target="_blank" href="https://firebase.google.com/docs/database/">_Store and sync data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available…_firebase.google.com</a><a target="_blank" href="https://platformio.org/"><strong>PlatformIO: An open source ecosystem for IoT development</strong></a><br><a target="_blank" href="https://platformio.org/">_Cross-platform build system and library manager. Cross-platform IDE and unified debugger. Remote unit testing and…_platformio.org</a><a target="_blank" href="https://www.arduino.cc/"><strong>Arduino - Home</strong></a><br><a target="_blank" href="https://www.arduino.cc/">_Open-source electronic prototyping platform enabling users to create interactive electronic objects._www.arduino.cc</a><a target="_blank" href="https://fezvrasta.github.io/bootstrap-material-design/"><strong>Bootstrap Material Design</strong></a><br><a target="_blank" href="https://fezvrasta.github.io/bootstrap-material-design/">_The most popular HTML, CSS, and JS Material Design library in the world._fezvrasta.github.io</a><a target="_blank" href="https://github.com/esp8266/Arduino"><strong>esp8266/Arduino</strong></a><br><a target="_blank" href="https://github.com/esp8266/Arduino">_ESP8266 core for Arduino. Contribute to esp8266/Arduino development by creating an account on GitHub._github.com</a><a target="_blank" href="https://github.com/FirebaseExtended/firebase-arduino"><strong>FirebaseExtended/firebase-arduino</strong></a><br><a target="_blank" href="https://github.com/FirebaseExtended/firebase-arduino">_Arduino samples for Firebase. Contribute to FirebaseExtended/firebase-arduino development by creating an account on…_github.com</a><a target="_blank" href="https://www.grc.com/fingerprints.htm"><strong>GRC | SSL TLS HTTPS Web Server Certificate Fingerprints</strong></a><br><a target="_blank" href="https://www.grc.com/fingerprints.htm">_GRC's HTTPS Web Server Certificate Fingerprint Service_www.grc.com</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An elegant LED illustration of a mathematical identity ]]>
                </title>
                <description>
                    <![CDATA[ By Chris Lam I am a big fan of science toys. I have been looking for one that combines the elegance of math and programming for a while. However, there was not much success in the search. So, I decided to make one myself. Here is a demo. The flashing... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-elegant-led-illustration-of-a-mathematical-identity-de88ee88c963/</link>
                <guid isPermaLink="false">66c343d74f1fc448a3678f90</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Electronics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Mathematics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 23 Nov 2018 19:10:21 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*jtP8OiDRsdDAdwBjyN5DGA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Chris Lam</p>
<p>I am a big fan of science toys. I have been looking for one that combines the elegance of math and programming for a while. However, there was not much success in the search. So, I decided to make one myself.</p>
<p>Here is a demo. The flashing LEDs are used to illustrate a mathematical identity visually.</p>
<h3 id="heading-math">Math</h3>
<p>The mathematical identity is the following. The left side of the equation is an arithmetic sum from 1 to <em>n-1</em> and the right side of the equation is “<a target="_blank" href="https://en.wikipedia.org/wiki/Combination">n choose 2</a>”, the number of unique ways to choose 2 items from <em>n</em> items.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*XZUYnypW2Qb9XLxW7VIC7g.png" alt="Image" width="600" height="400" loading="lazy">
<em>Mathematical identity</em></p>
<p>It is not the identity itself that is elegant, but the visual proof itself. Let’s look at the diagram below. There are <em>n=4</em> green dots in the illustration.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*jtP8OiDRsdDAdwBjyN5DGA.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>LED illustration</em></p>
<p>For every two green dots on the bottom row, there is always a unique red dot in the triangle above that corresponds to them. That red dot is the tip of an equilateral triangle with the base specified by the green dots.</p>
<p>Therefore, the number of ways to choose 2 green dots out of <em>n</em> green dots is equal to the sum of the red dots, 1 +2 + 3 + … + (<em>n</em>-1).</p>
<p>In this case, it is 1 + 2 + (4 –1) = 6.</p>
<p>This observation was originally made by Loren C. Larson in <a target="_blank" href="https://www.tandfonline.com/doi/abs/10.1080/07468342.1985.11972910?journalCode=ucmj20&amp;">this article</a>.</p>
<h3 id="heading-programming">Programming</h3>
<p>While it is easy to trace the red dot from the green dots visually, it is more fun and challenging to specify the relationship in code.</p>
<p>Let us assume that we know the indices of the green dots (say, i and j). The programming challenge is to specify the corresponding index of the red dot that forms the equilateral triangle with the green dots.</p>
<p>It looks difficult at first glance.</p>
<p>But the problem can be simplified a lot when we tweak the way that we label the red dots. We can label the red dots from bottom-up instead of top-down.</p>
<p>With that indexing scheme, we can then specify the index of the red dots by the following formula.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*cNwsj8hBqeC6HF1pz1dotg.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>An illustration of how to index the red dots using the indices of the green dots.</em></p>
<p>Here is the complete code used to flash the LEDs using Arduino.</p>
<h3 id="heading-electronics">Electronics</h3>
<p>I solder the LEDs on a board and connect the LEDs to Arduino output pins through 1k resistors. It is very important to use the resistors because they protect the LEDs.</p>
<p>The connection is as follows.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*AGo0vjfM8z5LmZmtOXMiJQ.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Schematics</em></p>
<p>And when you put them together and load the software to Arduino, it will start flashing like below.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*xggk2l3AY4vi5ZtN-KZYgw.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Final result</em></p>
<p>Hope you enjoy this gadget!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to use Arduino to check your web server’s response status ]]>
                </title>
                <description>
                    <![CDATA[ By Harshita Arora Last year, I created Crypto Price Tracker (an app which was acquired by Redwood City Ventures this year). A back end member of my team had been using an Arduino setup to check web server response statuses continuously to get updates... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-arduino-to-check-your-web-servers-response-status-9e47e02a61cc/</link>
                <guid isPermaLink="false">66c35597a6c3eebadae8d2dd</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Electronics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 19 Sep 2018 21:13:47 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*bQ91iaTCYt1SEHw-S3Rmxg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Harshita Arora</p>
<p>Last year, I created <a target="_blank" href="https://itunes.apple.com/us/app/crypto-price-tracker/id1333696099?ls=1&amp;mt=8">Crypto Price Tracker</a> (an app which was acquired by Redwood City Ventures this year). A back end member of my team had been using an Arduino setup to check web server response statuses continuously to get updates all the time. I found that setup to be pretty useful and interesting.</p>
<p>I researched about it and recreated the setup for myself. In this article, I’ll show you how you can build it yourself, too.</p>
<h4 id="heading-things-that-you-need">Things that you need:</h4>
<ol>
<li><a target="_blank" href="https://store.arduino.cc/usa/arduino-uno-rev3">Arduino Uno</a></li>
<li><a target="_blank" href="http://a.co/d/cLNijNF">Ethernet Shield for Arduino</a> (to connect the Arduino to the Internet)</li>
<li>Ethernet Cable</li>
<li>A/B Type USB 2.0 Cable (Power cable for Arduino)</li>
<li>Male-to-Male Jumper Cables (x2)</li>
<li>Breadboard</li>
<li>LED (x1, any color)</li>
<li>Resistor (x1, &gt;100 ohms works)</li>
</ol>
<h4 id="heading-setting-it-up">Setting It Up</h4>
<ol>
<li>Mount/Insert the Ethernet shield on the Arduino.</li>
<li>Insert the positive (longer) end of the LED into the breadboard slot 6a and the negative (shorter) end into slot 5a.</li>
<li>Insert one end of the <strong>resistor</strong> into the breadboard slot 1b and the other into slot 5b.</li>
<li>Insert one end of the <strong>first</strong> jumper cable into the breadboard slot 1e. Insert the other end into the GND slot of the Ethernet shield.</li>
<li>Insert one end of the <strong>second</strong> jumper cable into the breadboard slot 6e. Insert the other end into pin slot 2 of the Ethernet shield.</li>
<li>Connect the <strong>Ethernet</strong> cable from your router to your Ethernet shield.</li>
</ol>
<p>This is what my setup looks like:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*qbA3umNhKDiZy1bBrQZy1g.jpeg" alt="Image" width="600" height="400" loading="lazy"></p>
<ol start="7">
<li><p>Open a command line interface on your machine and check and note your default gateway. This can be done using <code>ipconfig</code> command on Windows or the <code>netstat -nr | grep default</code> command on Linux/Mac.</p>
</li>
<li><p>Download and install the Arduino IDE if you haven’t already.</p>
</li>
<li><p>Open the IDE and go to Files <code>-&amp;</code>gt; Exampl<code>es</code> -&gt; Eth<code>er</code>net -&gt; WebClientRepeating. You should see the following code:</p>
</li>
<li><p>Edit the <strong>line 37</strong> to be an IP address in the range (1–254) of your default gateway IP. So for example, if my default gateway is 10.0.0.1, then I can use an IP address from 10.0.0.2 to 10.0.0.254. It is, however, important to make sure that the IP that you’re using doesn’t conflict with any other IP addresses on your network.</p>
</li>
</ol>
<p>For this example, I changed the line of code to be:</p>
<p><code>**IPAddress ip(10, 0, 0, 2);**</code></p>
<ol start="11">
<li>Change the DNS in <strong>line 40</strong> to be <strong>8.8.8.8</strong> (this is the Google Public DNS and is just something I prefer, you may use a DNS that you prefer).</li>
</ol>
<p>For this example, I changed the line of code to be:</p>
<p><code>**IPAddress myDns(8, 8, 8, 8);**</code></p>
<ol start="12">
<li>Change the URL in <strong>line 45</strong> to a URL matching your web server. If you would like to use an IP address instead, then comment <strong>line 45</strong> and uncomment <strong>line 46</strong>. Since I am using a web server that I’m hosting locally, for this example, I will use an IP address.</li>
</ol>
<p>For this example, I changed the line of code to be:</p>
<p><code>//char server[] = “[www.arduino.cc](http://www.arduino.cc)";</code><br><code>IPAddress server(127,0,0,1);</code></p>
<p>Note that the port or the path here is not important yet. Just the IP Address<br>is needed. If you would like to change the port that is used for the GET<br>request, you may change it on <strong>line 94</strong>.</p>
<p>For this example, I have hosted my local webserver on port 3000. Thus, I will change the code in <strong>line 94</strong> to something like this:</p>
<p><code>if (client.connect(server, 3000)) {</code></p>
<ol start="13">
<li>Edit the <strong>GET</strong> request that is pre-written in <strong>lines 97 - 100</strong> to follow this pattern:</li>
</ol>
<p><code>client.println(“GET /path_to_url HTTP/1.1”);</code><br><code>client.println(“Host: 127.0.0.1”);</code><br><code>client.println(“Connection: close”);</code><br><code>client.println();</code></p>
<ol start="14">
<li>We can now start programming the behaviour of the LED depending on the web server status and response. To do this, we must first declare the pin we’re using for the LED on our Ethernet shield.</li>
</ol>
<p>Add the following line of code after the first two <strong>include</strong> statements of the program:</p>
<p><code>int LED = 2;</code></p>
<ol start="15">
<li>Add the following lines of code at the beginning of the <em>setup()</em> function.</li>
</ol>
<p><code>pinMode(LED, OUTPUT);</code></p>
<p><code>digitalWrite(LED, LOW); //program starts with the LED turned off</code></p>
<ol start="16">
<li>Add the following line of code after the GET request line that we previously edited:</li>
</ol>
<p><code>digitalWrite(LED, LOW);</code></p>
<ol start="17">
<li>Finally, add this line of code at the beginning of the <strong>else</strong> statement of the same conditional:</li>
</ol>
<p><code>digitalWrite(LED, HIGH);</code></p>
<p>And voilà, you’re done!</p>
<p>Upload the program to your Arduino. Open the serial monitor from the top right part of the IDE and watch the response. If your server doesn’t respond, the LED glows, if it does, the LED stays off :)</p>
<p>You can check out my final code <a target="_blank" href="https://gist.github.com/harshitaarora/1e096fe2ba7915964742e3f324f15184">here</a>.</p>
<h4 id="heading-checking-response">Checking Response</h4>
<p>If you would also like to <strong>validate</strong> the response that you receive from your<br>web server, then you may add them inside the following conditional of the<br>program.</p>
<p><code>if (client.available()) {</code><br><code>char c = client.read();</code><br><code>Serial.write(c);</code><br><code>}</code></p>
<p>The variable <strong>c</strong> is where the response is stored.<br>You could check it like this:</p>
<p><code>if (client.available()) {</code></p>
<p><code>char c = client.read();</code><br><code>if(c == “arduino is great”){</code><br> <code>digitalWrite(LED, LOW); //correct response</code><br><code>}</code><br><code>else{</code><br><code>digitalWrite(LED, HIGH); //wrong response</code><br><code>}</code><br><code>Serial.write(c);</code><br><code>}</code></p>
<p>Do note that, if you’re trying to do this, then it’s best to get rid of the<br>digitalWrite statement after the GET request. Depending on your response,<br>you may also have to parse JSON values. There are several ways to do this<br>and plenty of tutorials/articles around for it too! Make sure to check them<br>out!</p>
<p>Have fun! Feel free to email me at <code>harshita (at) harshitaapps.com</code> for any questions, feedback, or ideas!</p>
<p>Make sure to check out <a target="_blank" href="https://itunes.apple.com/us/app/crypto-price-tracker/id1333696099?ls=1&amp;mt=8">Crypto Price Tracker</a> app if you’re interested/invested in cryptocurrencies! :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to make a realtime light monitor using Arduino and Pusher ]]>
                </title>
                <description>
                    <![CDATA[ By Neo Ighodaro The Internet of Things (IoT) is changing the way we live, from wearable tech to smart home devices. IoT may sound complex, but in actuality it’s a fairly simple concept to understand. Everyday objects are constantly being transformed ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-a-realtime-light-monitor-using-arduino-and-pusher-2ec01524ec6a/</link>
                <guid isPermaLink="false">66c3534addebf8cbc124cb98</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ iot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 30 May 2018 22:09:36 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*xnDjT_FF-5OBCrTgHBF6aA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Neo Ighodaro</p>
<p>The Internet of Things (IoT) is changing the way we live, from wearable tech to smart home devices. IoT may sound complex, but in actuality it’s a fairly simple concept to understand. Everyday objects are constantly being transformed into smart devices using sensors and actuators.</p>
<p>In this article, we will build a realtime Arduino ambient light monitor which sends its sensor readings to a web application. We will cover the basics of connecting an Arduino board to the web and sending data as realtime notifications to a web app using Pusher.</p>
<p>This article will act as an introduction to what can be achieved with Arduino and Pusher. It is for those curious about the hardware industry who want to delve into the fun IoT world.</p>
<h3 id="heading-requirements-for-building-our-arduino-and-pusher-integration">Requirements for building our Arduino and Pusher integration</h3>
<p>In this process, I used:<br> — An Arduino board. MKR1000 board.<br> — <a target="_blank" href="https://www.arduino.cc/en/Main/Software">The Arduino IDE</a>.<br> — Photocell (available <a target="_blank" href="https://www.sparkfun.com/products/9088">here</a>).<br> — 10k Ohm resistor (available <a target="_blank" href="https://www.sparkfun.com/products/8374">here</a>).<br> — Breadboard and Jumper Wires.<br> — A Pusher application — <a target="_blank" href="https://pusher.com/developers">Create one here</a>.<br> — Composer (available for download at <a target="_blank" href="https://getcomposer.org">https://getcomposer.org).</a>.)<br> — Knowledge of PHP.</p>
<p>A breadboard is a board for temporarily prototyping hardware projects. It has nodes that conduct current throughout it.</p>
<p>The jumper wires are used for ensuring continuity between various points on the breadboard that aren’t connected by default.</p>
<h3 id="heading-getting-started-with-arduino">Getting Started with Arduino</h3>
<p>In this section, will set up the Arduino IDE and add internet connectivity to our board. We will find out about choosing the right board and adding internet connectivity to it.</p>
<p>Many of the boards don’t come with internet connectivity, which is something you need to make IoT devices. To add internet connectivity to our board, we have a variety of options to choose from: a shield, micro-chip, or an Arduino board with built-in wireless capabilities.</p>
<p>Note: a shield is basically an extension board that can be placed (mounted) on top of the Arduino board.</p>
<p>There are many types of shields:</p>
<pre><code><span class="hljs-number">1.</span> Ethernet Shield.
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1FMr9efK4eZjXE0bcKcVE9tx0PsE8NH2bbjv" alt="Image" width="600" height="400" loading="lazy">
_[Ethernet shield](https://www.digikey.com/en/articles/techzone/2012/jan/networking-options-for-arduino-based-systems" rel="noopener" target="<em>blank" title=")</em></p>
<pre><code><span class="hljs-number">2.</span> WiFi Shield.
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/ZIgAHwpMZ9P-IqYxcVzdzi-QyD7o17409uan" alt="Image" width="600" height="400" loading="lazy">
_[WiFi shield](https://store.arduino.cc/usa/arduino-wifi-shield" rel="noopener" target="<em>blank" title=")</em></p>
<pre><code><span class="hljs-number">3.</span> <span class="hljs-number">3</span>G or LTE Shields.
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/GwHUDbf7glVytuUviQG3yOzD7mrexSl-SoO4" alt="Image" width="520" height="330" loading="lazy">
_[Arduino GSM Shield](https://store.arduino.cc/usa/arduino-gsm-shield" rel="noopener" target="<em>blank" title=")</em></p>
<p>We are going to use the <a target="_blank" href="https://store.arduino.cc/usa/arduino-mkr1000">Arduino MKR1000</a> which comes with an in-built WiFi Chip. This board is available at the <a target="_blank" href="https://store.arduino.cc/usa/arduino-mkr1000">Arduino Store.</a></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/gktBy89jXSm5YJ2pwsrSZYwauHowuenln1oG" alt="Image" width="600" height="400" loading="lazy">
_[Arduino MKR1000 WIFI](https://store.arduino.cc/usa/arduino-mkr1000" rel="noopener" target="<em>blank" title=")</em></p>
<p>Next, download the Arduino IDE from <a target="_blank" href="https://www.arduino.cc/en/Main/Software">here</a> and install it on your computer.</p>
<p>Once the installation is finished, go ahead to install the <strong>Board Definition</strong> by launching the IDE. Then go to <code>Tools &gt; Boards &gt; Board M</code>anager where we search for and install the definitions for the MKR1000.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0m4FT25IL50oHvtPHAsRIGlXUanzJLXdkULq" alt="Image" width="787" height="497" loading="lazy">
<em>Board Manager</em></p>
<p>Once the <strong>Board Definition</strong> is completely installed, go to <code>Tools | Boards</code> and select the newly installed board definition.</p>
<p>To connect our Arduino Board to the internet, we have to install a library called <code>wifi101</code>. In order to install the library, go to <code>Sketch</code> <code>&amp;</code>g<code>t; Include Libr</code>a<code>r</code>y <code>&gt; Manage Lib</code>raries, then search for and in<code>stall w</code>ifi101.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/haRKcTrKvdKLWCcZaTxS8rLhmJAOkaDnSRzH" alt="Image" width="782" height="514" loading="lazy">
<em>Install WiFi101 library</em></p>
<p>We can test that it works by going to <code>Files &gt; Examples &gt; WiFi &gt; Conne</code>ctWithWpa. This should generate some code in our sketch. Next, <code>edit</code> the <code>ssid</code> and pass to our router’s SSID and Password:</p>
<pre><code>char ssid[] = <span class="hljs-string">"yourNetwork"</span>;     <span class="hljs-comment">//  your network SSID (name)    char pass[] = "secretPassword";  // your network password    int status = WL_IDLE_STATUS;     // the Wifi radio's status</span>
</code></pre><h3 id="heading-building-the-light-monitor-in-arduino">Building the Light Monitor in Arduino</h3>
<p>In this section, we are going to see how to set up the circuit and measure data coming from the sensors on the MKR1000 board. In addition to the Arduino MKR1000 and the usual breadboard and jumper wires, we are going to need a few extra components.</p>
<ul>
<li><a target="_blank" href="https://www.sparkfun.com/products/9088">Photocell</a></li>
<li><a target="_blank" href="https://www.sparkfun.com/products/8374">10k Ohm resistor</a></li>
</ul>
<p>The photocell is a sensor that allows us to detect light. They are often regarded as Light-Dependent Resistors (LDR), Photoresistors, or CdS cells.</p>
<p>A Photocell is basically a resistor that changes its resistive value (in ohms) depending on how much light is shining onto the squiggly face.</p>
<h4 id="heading-assembling-the-components"><strong>Assembling the components</strong></h4>
<p>First, place the resistor in series with the photocell on the breadboard, next to the Arduino board.</p>
<p>Now, connect the other end of the resistor to GND on the Arduino board, and the other end of the photocell to the VCC pin of the Arduino board.</p>
<p>Finally, connect the middle pin between the resistor and the photocell to analog pin A0 of the Arduino board. The final result should look like this:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/osntZEkqFYLTPicQfUU5XUvlezFBbqT2Xg7I" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once this is done, we can go ahead and configure the board to read data coming from the photocell. We will take the readings from analog pin A0 and print them on the serial port for now. The sketch for this part is really easy and should look like this:</p>
<p>We will copy and paste this sketch into our Arduino IDE, then upload it to the board.</p>
<p>Make sure the right board and serial ports are selected.</p>
<pre><code><span class="hljs-comment">// Pins    int sensorPin = A0;    void setup() {      // Serial      Serial.begin(115200);    }</span>
</code></pre><pre><code>    <span class="hljs-keyword">void</span> loop() {      <span class="hljs-comment">// Reading      int sensorValue = analogRead(sensorPin);      // Display      Serial.print("Sensor reading: ");      Serial.println(sensorValue);      // Wait      delay(500);    }</span>
</code></pre><p>You can <strong>save the Arduino sketch files to your machine</strong>, so you can reference them later. They can be named whatever you like as long as they are uploaded to the Arduino board.</p>
<p>After this is run, we open the serial monitor and immediately observe the readings from the sensor:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/K-OeEYRaA7PP9HZy3TAKbTohDqe6-gCVP2Oc" alt="Image" width="571" height="249" loading="lazy"></p>
<p>If we put our hands over the sensor, we will see a decrease in the values measured by it. Now let’s focus on creating the web application.</p>
<h3 id="heading-setting-up-the-web-application">Setting up the web application</h3>
<p>In this section, we are going to create a basic web application that collects the data as a <code>GET</code> request and displays it to the users subscribed to that channel in realtime. For realtime display we’ll be using <a target="_blank" href="http://pusher.com">Pusher</a>.</p>
<p>Pusher is a simple hosted API for quickly, easily, and securely integrating realtime bi-directional functionality via WebSockets to web and mobile apps, or any other Internet-connected device.</p>
<p>The first step will be to create a free Pusher account. If you don’t have one, then create your application on the <a target="_blank" href="https://dashboard.pusher.com">dashboard</a>.</p>
<h4 id="heading-creating-a-pusher-application"><strong>Creating a Pusher application</strong></h4>
<p>Create a Pusher account and go to Your apps &gt; Create new app. Fill in your application name, select a cluster, choose JavaScript and PHP, and then we are good to go.</p>
<p>The application set up screen should look something like this:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/R5woGfHJG7bDg0AVOKuBTeXPTULtVqidi-9u" alt="Image" width="755" height="673" loading="lazy"></p>
<p>Once done, you will be provided with your App keys.</p>
<h4 id="heading-setting-up-our-project"><strong>Setting up our project</strong></h4>
<p>We’ll create a folder called <code>arduino-light-monitor</code> in our <code>localhost</code> root directory.</p>
<p>Then, open your terminal and type <code>composer require pusher/pusher-php-server</code>. This will generate a couple of files in our directory.</p>
<p>Create a file called <code>notification.html</code>. Then add the HTML and JavaScript below:</p>
<pre><code>&lt;!DOCTYPE html&gt;    &lt;html&gt;    &lt;head&gt;      &lt;title&gt;Notifications From Light monitor&lt;/title&gt;      &lt;script src="https://js.pusher.com/4.1/pusher.min.js"&gt;&lt;/script&gt;      &lt;script&gt;        //Enable Pusher Logging - don't include this in production        Pusher.logToConsole = true;
</code></pre><pre><code>        <span class="hljs-comment">//Create a new instance of pusher with your credentials        var pusher = new Pusher('APP_KEY', {            cluster: 'PUSHER_CLUSTER',//if you chose a different cluster replace it here            encrypted: true          });</span>
</code></pre><pre><code>        <span class="hljs-comment">//subscribe to a channel you will listen on        var channel = pusher.subscribe('light-monitor-channel');</span>
</code></pre><pre><code>        <span class="hljs-comment">//What happens when light-readings-sent is fired        channel.bind('light-readings-sent', function(data){          //gets the ul in the dom          var ul = document.querySelector('ul');          //creates a li          var li = document.createElement('li');          //Attaches the data received to the text node          var itemText = document.createTextNode(data.value);          //Append the data to the li          li.appendChild(itemText);          //Append the li to the ul          ul.appendChild(li);        });      &lt;/script&gt;    &lt;/head&gt;    &lt;body&gt;      &lt;ul&gt;&lt;/ul&gt;    &lt;/body&gt;    &lt;/html&gt;</span>
</code></pre><p>What happens here is we subscribe to a channel called <code>light-monitor-channel</code> then wait until we receive an event called <code>light-readings-sent</code>. Whenever the event is triggered, we append the data received to our list.</p>
<p>We will also create another file called <code>index.php</code>. This is the file that will send the events to the notifications channel. We will add the PHP code below to the file:</p>
<pre><code>&lt;?php      <span class="hljs-built_in">require</span> __DIR__ . <span class="hljs-string">'/vendor/autoload.php'</span>;
</code></pre><pre><code>      $options = array(        <span class="hljs-string">'cluster'</span> =&gt; <span class="hljs-string">'PUSHER_APP_CLUSTER'</span>,        <span class="hljs-string">'encrypted'</span> =&gt; <span class="hljs-literal">true</span>      );      $pusher = <span class="hljs-keyword">new</span> Pusher\Pusher(        <span class="hljs-string">'PUSHER_APP_KEY'</span>,<span class="hljs-comment">// replace with yours        'PUSHER_APP_SECRET',//replace with yours        'PUSHER_APP_ID', //replace with yours        $options      );</span>
</code></pre><pre><code>      <span class="hljs-comment">//checks if there is any data sent      if(isset($_GET['value'])){        $data['value'] = $_GET['value'];        //triggers the event on the channel        $pusher-&gt;trigger('light-monitor-channel', 'light-readings-sent', $data);      } else {        echo "Nothing to do";      }    ?&gt;</span>
</code></pre><p>If you need somewhere to host your content, you can go to <a target="_blank" href="http://000webhost.com">000webhost.com</a> and create a free subdomain where you can upload the contents of your arduino-light folder.</p>
<p>We will test it out by opening <code>notification.html</code> and <code>index.php</code> in two different browsers. When we reload <code>index.php</code>, we should get a new list item added with a value of “Empty request”. If we try <code>index.php?value=123</code>, we should get <code>value 123</code> added to our notifications list in realtime.</p>
<p>Isn’t that just awesome?</p>
<h3 id="heading-sending-the-sensor-readings-to-the-web-app">Sending the sensor readings to the web app</h3>
<p>Finally, we will look at how to send the data from the Arduino board to the server.</p>
<p>Continuing from the sketch we had before, we just replace this by taking note of the important parts:</p>
<pre><code><span class="hljs-comment">// Pins    int sensorPin = A0;</span>
</code></pre><pre><code>    char ssid[] = <span class="hljs-string">"wifi_name"</span>; <span class="hljs-comment">//your wifi name    char pass[] = "wifi_pass"; // your wifi password    int status = WL_IDLE_STATUS;</span>
</code></pre><pre><code>    char server[] = <span class="hljs-string">"yourexampleserver.com"</span>; <span class="hljs-comment">//replace with your localhost or domain</span>
</code></pre><pre><code>    <span class="hljs-comment">// Create an instance of WiFiClient    WiFiClient client;</span>
</code></pre><pre><code>    <span class="hljs-comment">// We define the interval on which we want to send the data    unsigned long lastConnectionTime = 0;    const unsigned long postingInterval = 60L * 1000L; //this implies 60,000L the L represents the long datatype</span>
</code></pre><pre><code>    <span class="hljs-keyword">void</span> setup() {      <span class="hljs-comment">// Serial      Serial.begin(115200);</span>
</code></pre><pre><code>      <span class="hljs-comment">// Attempt to connect to Wifi network:      while ( status != WL_CONNECTED) {</span>
</code></pre><pre><code>        Serial.print(<span class="hljs-string">"Attempting to connect to WPA SSID: "</span>);        Serial.println(ssid);
</code></pre><pre><code>        <span class="hljs-comment">// Connect to WPA/WPA2 network:        status = WiFi.begin(ssid, pass);</span>
</code></pre><pre><code>        <span class="hljs-comment">// Wait 10 seconds for connection:        delay(10000);      }</span>
</code></pre><pre><code>      <span class="hljs-comment">// you're connected now      Serial.print("You're connected to the network");    }</span>
</code></pre><pre><code>    <span class="hljs-keyword">void</span> loop() {      <span class="hljs-keyword">if</span>(millis() - lastConnectionTime &gt; postingInterval) {        <span class="hljs-comment">//Measure the light level        int sensorValue = analogRead(sensorPin);</span>
</code></pre><pre><code>        <span class="hljs-comment">//Send the value to the server        sendHTTPRequest(sensorValue);      }    }</span>
</code></pre><pre><code>    <span class="hljs-keyword">void</span> sendHTTPRequest(int sensorValue){      <span class="hljs-comment">// Close existing connection      client.stop();</span>
</code></pre><pre><code>      <span class="hljs-comment">// Connect &amp; send request      if (client.connect(server, 80)) {</span>
</code></pre><pre><code>        Serial.println(<span class="hljs-string">"connecting..."</span>);
</code></pre><pre><code>        <span class="hljs-comment">// Send the HTTP GET request:        client.println("GET /light/?value=" + String(sensorValue) + " HTTP/1.1");        client.println("Host: yourexampleserver.com");        client.println("User-Agent: ArduinoWiFi/1.1");        client.println("Connection: close");        client.println();</span>
</code></pre><pre><code>        <span class="hljs-comment">// Note the time that the connection was made:        lastConnectionTime = millis();      }      else {        // if you couldn't make a connection:        Serial.println("connection failed");      }    }</span>
</code></pre><p>In the code above, we create a connection to the specified WiFi <code>ssid</code> using an instance of <code>WiFiClient</code>. We will use this connection to interact with our remote server.</p>
<p>In the <code>setup``()</code> function, we deal with the initialization of the <a target="_blank" href="https://www.arduino.cc/reference/en/language/functions/communication/serial/">Serial</a> and connection to the WiFi network specified by the <code>ssid</code> and <code>pass</code> variables above.</p>
<p>In the <code>loop``()</code> function we check if we are in the posting interval. Then, if we are, we take the reading and make a call to the <code>sendHTTPRequest</code> function defined below it.</p>
<p>In the <code>sendHTTPRequest``()</code> function, we accept a parameter called <code>sensorValue</code>. Because Arduino runs the code in a loop, the first thing to do is to stop any previous opening of the client connection with the statement <code>client.stop()</code>. This will stop connections from being created and will keep them from being discarded after they have been used.</p>
<p>Next, we try to connect to the server defined in the variable <code>server[]</code>. We check if the connection can be established, and if not we print to the Serial “connection failed”. Once the client is connected, we send the sensor pin value through the URL to our web application.</p>
<p>If we test this out now, we will have the light sensor reading every minute.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xbLXp8j2TwoE7DG3MJggHJn7H-HaQCBLBT8v" alt="Image" width="213" height="193" loading="lazy"></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>We have successfully built a light monitor using Arduino and Pusher. If you enjoyed this tutorial and would like to go from zero to hero in the IoT world, you should check out the book <a target="_blank" href="https://www.packtpub.com/hardware-and-creative/internet-things-arduino-cookbook">“Internet of Things with Arduino Cookbook” by Marco Schwartz</a>. It contains over 60 recipes which will help you build smart IoT solutions and will surprise you with captivating IoT projects you thought only existed in James Bond movies.</p>
<p>If you have any questions or other ideas on integrating IoT with Pusher, please leave a comment below!</p>
<p>This was originally published on our <a target="_blank" href="https://blog.pusher.com/make-a-realtime-light-monitor-using-arduino-and-pusher/">blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to make a digital voltmeter using Arduino ]]>
                </title>
                <description>
                    <![CDATA[ By Harshita Arora Last Sunday, while I was explaining the basics of electronics and Arduino to my roommate, she challenged me to understand how a voltmeter works and build one from scratch just using the stuff I own already. I accepted the challenge,... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-a-digital-voltmeter-using-arduino-b4dbf5b94d6f/</link>
                <guid isPermaLink="false">66c3533fd58e4fdd567d51b5</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Electronics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 23 May 2018 17:34:47 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*Vnn6OGrwT4RHyHEwHBQI7Q.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Harshita Arora</p>
<p>Last Sunday, while I was explaining the basics of electronics and Arduino to my roommate, she challenged me to understand how a voltmeter works and build one from scratch just using the stuff I own already. I accepted the challenge, started hacking, coding, testing, re-coding, and re-testing, and finally I had my voltmeter ready and working by dinner time!</p>
<p>I used Arduino Uno (to collect voltage in analog and to power the LCD), a small LCD screen that I got in my Arduino starter kit (to display the voltage), a breadboard (to connect everything), and jumper wires.</p>
<p>If you’re looking for an easy project to learn electronics, then making a digital voltmeter will be fun. Let’s get started!</p>
<h3 id="heading-the-electric-circuit"><strong>The Electric Circuit</strong></h3>
<h4 id="heading-step-1">Step 1</h4>
<p>Take a breadboard (I used a small one with 30 rows) and connect an LCD screen to it. Then using a wire, connect one wire from the GND pin (ground state) on the Arduino to the negative charge on breadboard, and one wire from the 5V pin to the positive charge. This provides electric current to the columns on the breadboard, which we can now connect to the LCD.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SNHrp53F6h8pqVjr2-VY80Gs2Zhq44lZY8rU" alt="Image" width="600" height="400" loading="lazy">
<em>This is the basic setup after Step 1.</em></p>
<h4 id="heading-step-2">Step 2</h4>
<p>Now we’ll connect the pins on the LCD to the breadboard so we can get current to it. Connect Pin 1 of the LCD to a negative charge, Pin 2 to a positive charge, Pin 3 to a negative charge, Pin 5 to a negative charge, Pin 15 to a positive charge, and Pin 16 to a negative charge. Plug in your Arduino to test and see if the LCD turns on!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/T0WP8iFl9qbX-VnI0GYUhcL6OAhA8iSUYhOa" alt="Image" width="600" height="400" loading="lazy">
<em>The LCD lights up!</em></p>
<h4 id="heading-step-3">Step 3</h4>
<p>Let’s connect the LCD to the Arduino so that we can display the voltage (which we will collect from an analog pin) on the LCD. Connect Pins 4, 6, 11, 12, 13, and 14 of the LCD to any digital pin on Arduino (for example, Pin 2). Then put a wire in the GND and another in an analog pin, like A5. The two wires are now your probe leads.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/NW8m7mJlEFP7xsorvz6EW9Y35KRTDN1bjXTM" alt="Image" width="600" height="400" loading="lazy">
<em>Finished electric circuit!</em></p>
<p>We’re now done with the electronics/hardware. Let’s move on to the code.</p>
<h3 id="heading-the-code"><strong>The Code</strong></h3>
<p>The code is pretty simple. We just want to collect the analog signal that the Arduino receives at Pin A5 (or any other analog pin) and convert it to digital. We then want to display the results on the LCD screen.</p>
<p>This is the code that you can copy-paste.</p>
<pre><code>#include &lt;LiquidCrystal.h&gt; int Vpin=A5;float voltage;float volts;LiquidCrystal lcd(<span class="hljs-number">12</span>, <span class="hljs-number">11</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>);
</code></pre><pre><code><span class="hljs-keyword">void</span> setup() {Serial.begin(<span class="hljs-number">9600</span>);lcd.begin(<span class="hljs-number">16</span>,<span class="hljs-number">2</span>);}
</code></pre><pre><code><span class="hljs-keyword">void</span> loop() {
</code></pre><pre><code>voltage = analogRead(Vpin); volts = voltage/<span class="hljs-number">1023</span>*<span class="hljs-number">5.0</span>; Serial.println(volts);lcd.print(“voltage = “);lcd.print(volts);delay(<span class="hljs-number">200</span>);lcd.clear();}
</code></pre><p>What’s going on here?</p>
<p>So we’re first importing the LCD library, then creating a variable named Vpin (which will be the voltage collected from A5). Next, we create two more variables for the voltage, and then a variable of type LiquidCrystal. Finally, we do setup with the Serial monitor (which is a really useful tool in Arduino! Sort of like debug console), convert the analog voltage to digital voltage, and print (display) that value to the LCD screen.</p>
<p>And that’s it! Go and test out various batteries and points! Here are photos from some tests I did:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VOnX6XrnL4cNqEZ-aBzU0Aj8AtRiEYuf5YQb" alt="Image" width="600" height="400" loading="lazy">
<em>Neutral wires.</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/IUX4cbowtANkEPD2YBOzWv7tQUN63NJ0WNc3" alt="Image" width="600" height="400" loading="lazy">
<em>Testing a 1.5V AA battery.</em></p>
<p>Also, if you want to make the reading on the LCD more legible, put a 1k ohm resistor in the path to Pin 3 (which is for contrast adjustments). By limiting the electric current flowing to that pin, you’ll improve the contrast of the screen.</p>
<p><strong>Also important note</strong>: In this voltmeter, whatever voltage you test will go as a direct input to the Arduino, so you should only test stuff that is in the range of volts that Arduino can safely handle (0–5V). Testing with a 9V battery will fry your Arduino.</p>
<p>Thanks to this <a target="_blank" href="https://youtu.be/OZM6wm16uPU">video tutorial</a> for helping me figure out the electric circuit. Special thanks to my friends <a target="_blank" href="https://twitter.com/nickarner">Nick Arner</a> and <a target="_blank" href="https://twitter.com/johnny___wang">Johnny Wang</a> for helping me fix stuff. And thanks to <a target="_blank" href="https://twitter.com/LauraDeming">Laura Deming</a> for the challenge! :)</p>
<p>More articles and tutorials on electronics/hardware and brain-computer interfaces on the way! :D</p>
<p>If you have feedback to share, feel free to email me at harshita@harshitaapps.com. I look forward to hearing from you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Create an Arduino and Unity3D interactive experience with no latency !⏱ ]]>
                </title>
                <description>
                    <![CDATA[ By Maxime Coutte Hi, I’m 16 years old and during the holidays I like to work on little projects. I grew up in a very artistic environment - my father is a painter my brothers and sisters draw, play music, compose … And me, with my best friend we want... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/you-can-now-create-an-arduino-and-unity3d-interactive-experience-without-latency-2d7388dcc0c/</link>
                <guid isPermaLink="false">66c367c69aa4fb7920cb7dde</guid>
                
                    <category>
                        <![CDATA[ arduino ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DIY ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Unity3D ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 16 Dec 2017 13:35:22 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*GYnriIV-IBFyGDDIHjbQBA.gif" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Maxime Coutte</p>
<p>Hi, I’m 16 years old and during the holidays I like to work on little projects. I grew up in a very artistic environment - my father is a painter my brothers and sisters draw, play music, compose … And me, with my best friend we wanted to have fun with our new Arduino and Unity3D, so we started working on interactive artistic experiences. But we got stuck on one big thing. If you’ve ever wanted to transmit data from Arduino to Unity3D, you know the main issue is <strong>INSANE LATENCY</strong>.</p>
<h4 id="heading-dont-worry-about-latency-wrmhlhttpsgithubcomrelativtywrmhl-is-here">Don’t worry about Latency, <a target="_blank" href="https://github.com/relativty/wrmhl">wrmhl</a> is here ⚡️</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Eq8d7WJ-2ZRuoAtYB-3UtzLDkFKivnwklyUc" alt="Image" width="600" height="400" loading="lazy">
<em>Without wrmhl (using a simple ReadLine () )</em></p>
<p>We didn't find any free, optimized, and customizable solutions to tackle this problem. So I built <a target="_blank" href="https://github.com/relativty/wrmhl"><strong>wmrhl</strong></a>. You can now connect any Arduino interface to Unity3D, and it’s completly <strong>Open Source.</strong></p>
<ul>
<li>Just write your Arduino code, how about <a target="_blank" href="https://www.youtube.com/watch?v=ikD_3Vemkf0">A Touchless 3D Tracking Interface</a> or a <a target="_blank" href="http://openbci.com/">Brain-Computer Arduino Interface</a> ?</li>
<li>Add a Serial print to send data from your interface to Unity3D (<a target="_blank" href="https://github.com/relativty/wrmhl/blob/master/Arduino/Arduino.ino">see examples</a>)</li>
<li>Import wrmhl to Unity, and voilà!</li>
</ul>
<p>You can use the default wrmhl protocol, or implement your own in a minute just by changing: <a target="_blank" href="https://github.com/relativty/wrmhl/blob/master/Assets/WRMHL/Scripts/Thread/wrmhlThread_Lines.cs">wrmhl/Assets/WRMHL/Scripts/Thread/wrmhlThread_Lines.cs</a>.</p>
<h4 id="heading-how-to-get-started">How to get started ?</h4>
<p>just follow the guide by <a target="_blank" href="https://github.com/relativty/wrmhl#getting-started-%EF%B8%8F"><strong>clicking here</strong></a>. Star the repo if you liked it ⭐️</p>
<p>Hope this is helpful! If you’re using it, would love to hear about what you’re building. Ping me at <strong>maxime@relativty.com</strong> or <a target="_blank" href="https://twitter.com/maximecoutte">@maximecoutte</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
