<?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[ Ihechikara Abba - 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[ Ihechikara Abba - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 09:04:38 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Ihechikara/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Chess "Italian Game" Handbook: Traps for White ]]>
                </title>
                <description>
                    <![CDATA[ A chess game is usually divided into three phases: the opening, middlegame, and endgame. In the opening phase, each player develops and sets up their pieces. In the middlegame, they plan attacks, execute different tactics and strategies to gain an ad... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-chess-italian-game-handbook-traps-for-white/</link>
                <guid isPermaLink="false">69932b89881a983a8060252f</guid>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 16 Feb 2026 14:36:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1771252596669/88710fa6-d7b3-4914-ae0c-cafa7ea244a6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A chess game is usually divided into three phases: the opening, middlegame, and endgame.</p>
<p>In the opening phase, each player develops and sets up their pieces. In the middlegame, they plan attacks, execute different tactics and strategies to gain an advantage and weaken their opponent. In the endgame, there are usually few pieces left on the board, and each player tries to win using certain techniques and piece coordination.</p>
<p>In this handbook, you'll learn about opening traps for the Italian Game, which is one of the most played openings in chess.</p>
<p>When learning about openings, you're usually taught some basic principles, like:</p>
<ul>
<li><p>Control and fight for the center.</p>
</li>
<li><p>Develop pieces.</p>
</li>
<li><p>Castle the king early.</p>
</li>
<li><p>Connect the rooks.</p>
</li>
<li><p>Don’t bring the queen out early.</p>
</li>
<li><p>Avoid unnecessary pawn moves, and so on.</p>
</li>
</ul>
<p>These principles are easier said than done. Many beginners focus too much on implementing them and fall for obvious traps. That’s what this handbook will help you with.</p>
<p>Learning about an opening is as important as learning the common mistakes associated with each opening. You can learn a chess opening to improve your tactics and strategy, understand how to develop your pieces, and understand how to spot certain mistakes early so you can avoid them or take advantage of them.</p>
<p>This handbook will focus on those opening mistakes and how to take advantage of them when playing as white.</p>
<p>You can watch the <a target="_blank" href="https://youtu.be/NDdCrvC79eg">video version of this handbook here</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NDdCrvC79eg" 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-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-this-handbook">How to Use this Handbook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-this-handbook-will-teach-you">What this Handbook Will Teach You</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-this-handbook-will-not-teach-you">What this Handbook Will Not Teach You</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-traps">Traps</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-italian-game">The Italian Game</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-traps-in-the-italian-game">How to Create Traps in the Italian Game</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-1-giuoco-piano">Game #1 - Giuoco Piano</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-2">Game #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-3-legals-mate">Game #3 - Legal's Mate</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-4">Game #4</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-5-the-fried-liver-attack">Game #5 - The Fried Liver Attack</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-game-6-anti-fried-liver-defence">Game #6 - Anti-Fried Liver Defence</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-how-to-use-this-handbook">How to Use this Handbook</h2>
<p>This handbook makes use of notations and images. If you understand chess notations, then you can follow along without relying on the images. If you're new to notations, I'd recommend reading the What are Notations in Chess? chapter of <a target="_blank" href="https://www.freecodecamp.org/news/checkmate-patterns-in-chess-for-beginners/#heading-chapter-1-what-are-notations-in-chess-algebraic-chess-notation-explained">this handbook</a>.</p>
<p>In order to follow along, you should have a board with you. You can use either a physical board or an online chessboard. You can use <a target="_blank" href="https://lichess.org/">Lichess</a> for your online chessboard. Under the Tools section, you should see a couple of board related tools that you can make use of.</p>
<p>I would not recommend reading through without practicing. The best way to understand certain concepts is to try them out yourself.</p>
<p>And remember, improving in chess takes time and effort, so don't feel bad if you don't automatically start seeing gains. Focus on understanding and practicing first, and if you're doing that the right way, you'll gradually start progressing.</p>
<h2 id="heading-what-this-handbook-will-teach-you">What This Handbook Will Teach You</h2>
<p>This handbook will teach you some opening traps when playing the Italian Game as white. The overall purpose is for you to see common opening mistakes and how to take advantage of them. Even though you'll play as white in this case, you'll also learn why your opponents fall for these tricks, and that should help you avoid them when playing as black.</p>
<p>So, this is not an Italian Game opening handbook where we'll analyze lengthy games from start to finish. This is solely for beginners who want to understand why certain traps occur occasionally and why they always fall for them. You can learn something useful with this handbook irrespective of the color you play as.</p>
<h2 id="heading-what-this-handbook-will-not-teach-you">What This Handbook Will Not Teach You</h2>
<p>This handbook will not teach you how to follow basic opening principles to a tee. Sometimes, in order to win early and gain an advantage early in the game, you have to play unconventionally. These unconventional moves may prevent you from following certain principles.</p>
<p>You’ll not learn deeply about piece placement or pawn structure. These concepts are part of this handbook but we won’t focus much on them.</p>
<p>This guide will also not make reference to popular or model games. That is, won’t not make use of or analyze games that have been played by masters in the past. So, I won’t be explaining key moments from specific games.</p>
<h2 id="heading-traps">Traps</h2>
<p>Chess isn't scripted, so if you rely on your opponent to fall for certain tricks because you played the "right" moves from a course, then you may lose a lot of games. The traps here should not be seen as a conventional way of playing openings. It's important that you understand the concept behind the moves, as this will help you adjust your gameplay against anyone who knows how not to fall for traps.</p>
<p>In summary, don't memorize lines to use against opponents. Understand the concept and strategies first. Doing that will help you improve your tactics/strategy, and make it easier to spot similar positions in different games.</p>
<p>Let's get started!</p>
<h2 id="heading-the-italian-game">The Italian Game</h2>
<p>The Italian Game is a very popular chess opening used by players across all levels of chess. The opening allows you to quickly develop your pieces and move them to active positions, and gain control of the center.</p>
<p>The Italian Game starts with these lines:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3</p>
</li>
</ol>
<p>Bringing the knight to f3 attacks the pawn on e5, which leads to black playing:</p>
<ol start="2">
<li>... Nc6</li>
</ol>
<p>This defends the e5 pawn.</p>
<ol start="3">
<li>Bc4</li>
</ol>
<p>Finally, the bishop is moved the c4, and here's what the position looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706417111/efb650a7-c1cd-4864-af48-230992b198c1.png" alt="Italian Game starting position" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<p>When you reach the position in the image above, you've entered the Italian Game opening. Let's analyze white's position.</p>
<p>White has developed two minor pieces and a pawn, and has made way for castling and protecting the king early in the game. White is not wining yet, but that could quickly change depending on what black plays.</p>
<ol start="3">
<li>... Bc5</li>
</ol>
<p>This position leads to a variation of the Italian Game known as Giuoco Piano, and it’s played very often. In fact, it’s the most played variation of the Italian Game. We’ll start with that variation in the next section.</p>
<h2 id="heading-how-to-create-traps-in-the-italian-game">How to Create Traps in the Italian Game</h2>
<p>In this section, you'll learn some common traps for the Italian Game. We'll start with the Giuoco Piano variation.</p>
<h2 id="heading-game-1-giuoco-piano">Game #1 - Giuoco Piano</h2>
<p>Here's the starting position of the Giuoco Piano variation:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706451508/f783ad3e-658b-4f91-bb8e-8dbabf1b500c.png" alt="Giuoco Piano variation of the Italian Game" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<ol start="4">
<li>c3</li>
</ol>
<p>Moving the pawn to c3 provides support for the d-file pawn, which can threaten the bishop on c5 and gain control of the center.</p>
<ol start="4">
<li>... Nf6</li>
</ol>
<p>With that, the black knight threatens to capture the pawn on e4 and clears the way for castling.</p>
<p>Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706486975/cd1132db-4174-4ceb-aca7-9365c5722e66.png" alt="black moves knight to f6 and threatens the pawn on e4" class="image--center mx-auto" width="703" height="700" loading="lazy"></p>
<p>What should you play here? Well, this section is about tricks. The safest move here would be d3 – this keeps things balanced, protects the e-pawn, and allows you to continue developing your pieces. But we're not going for a balanced or safe development.</p>
<ol start="5">
<li>d4</li>
</ol>
<p>This move forces black to capture on d4. If black chooses to move the bishop to a different square like Bb6, then we'll have something like 6. dxe5 Ng4, 7. Bxf7+ Kxf7, 8. Ng5+ Ke8. Black can't castle at the moment, as white is trying to gain more control of the center and can easily start attacking from the kingside. So retreating with the bishop isn't a good move for black. Although black can move the bishop to other squares and have a different outcome, white still gains an advantage.</p>
<ol start="5">
<li><p>... exd4</p>
</li>
<li><p>cxd4</p>
</li>
</ol>
<p>That brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706502296/692c8aad-4907-4fa3-b334-db3d55a23228.png" alt="the white c-pawn captures the black d-pawn" class="image--center mx-auto" width="705" height="702" loading="lazy"></p>
<p>Again, retreating with the bishop puts black at a disadvantage. For example, 6. ...Bb6, 6. ...Bd6, or 6. ...Be7 will simply allow white to start attacking with the pawns in the center of the board. The worst move here would be 6. ...Bf8, which both blocks black from castling and allows white to start attacking from the center.</p>
<p>The best move for black would be to check the king:</p>
<ol start="6">
<li>... Bb4+</li>
</ol>
<p>This is a crucial point for the trap. The safest move here is 7. Nd2. This protects the king and keeps the game balanced. But again, we're not playing it safe this time.</p>
<ol start="7">
<li>Nc3</li>
</ol>
<p>Let's look at the position visually:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706524493/c29f4a75-575a-4ce8-abbd-52140a2c2235.png" alt="white moves knight to c3 to block the check" class="image--center mx-auto" width="703" height="702" loading="lazy"></p>
<p>This position gives black a slight advantage. In order to set the perfect trap for your opponent, you may have to sacrifice some of your pieces and give them some false advantage. This doesn't mean that every trap will work – so make sure to evaluate your position well before taking chances.</p>
<p>With Nc3, white gives up the e4 pawn. This position is known as the Greco's Gambit. The main purpose of the move is to lure your opponent into capturing the e4 pawn with its knight.</p>
<ol start="7">
<li>... Nxe4</li>
</ol>
<p>This is a common response. Without getting rid of that pawn, white can start attacking with the pawns and make black's opening a bit difficult. So how do you respond? Remember, we're playing a gambit, which involves sacrificing a piece, usually a pawn, in the beginning of the game in order to gain an advantage.</p>
<p>Since black has accepted the gambit by capturing that pawn, we can continue with the plan.</p>
<ol start="8">
<li>O-O</li>
</ol>
<p>Now that the king has been safely castled, a couple of things have changed:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706537110/a4e3958f-4088-4b41-b102-e5e6385f9e0c.png" alt="white castle" class="image--center mx-auto" width="703" height="702" loading="lazy"></p>
<p>The knight on c3 is no longer pinned to the king, and if black castles, it'll lose the e4-knight. The best move here for black is to capture with the bishop. This is something you should always remember when playing as black in this position. White starts gaining some advantage if black captures with the knight, and that's what we'll use to learn about the trap here.</p>
<ol start="8">
<li><p>... Nxc3</p>
</li>
<li><p>bxc3 Bxc3</p>
</li>
</ol>
<p>We've managed to lure black into the trap by sacrificing more pieces. Black is threatening the a1-rook, but we're not going to try and save it. Since the purpose of a gambit is to gain advantage, we must capitalize on doing just that. If you try saving the a1-rook, then black will simply castle and you'd be in a slightly losing position.</p>
<ol start="10">
<li>Ba3</li>
</ol>
<p>This prevents black from castling the king. Here's what the current position looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706548912/6863e580-f88a-4c5d-820b-0cbc97f302a8.png" alt="white bishop moves to c3 to block black from castling" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>White already has more advantage in this position and is giving up the a1-rook. If black decides to block the a3-bishop with 10. ...d6, then black would lose its bishop after 11. Rc1 Ba5 12. Qa4 Bd7 13. d5 Nd4 14. Qxa5. This is another variation you can learn, in case black doesn't capture the bishop. But don't rely on these to always work – you're better off understanding the strategy behind these attacks than trying to replicate them all the time.</p>
<ol start="10">
<li>... Bxa1</li>
</ol>
<p>This is the moment we've been waiting for all along.</p>
<ol start="11">
<li>Re1+</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706562361/850f0037-711a-4060-b850-1ab7c858dcc7.png" alt="rook check on the black king" class="image--center mx-auto" width="700" height="702" loading="lazy"></p>
<p>Black can only defend the king with the knight or the queen. Neither of those moves will make black's position any better. Naturally, defending with the knight would be the first option (although I would suggest resigning if you're playing as black in this position against a player who knows what they're doing).</p>
<ol start="11">
<li>... Ne7</li>
</ol>
<p>As white, you can either play 12. Bxe7 or 12. Rxe7. The former would lead to a black losing its queen after 12. ...Qxe7, 13. Rxe7+.</p>
<ol start="12">
<li>Rxe7</li>
</ol>
<p>The best option for black would be to lose the queen by capturing the e7-rook. Not that it gives black any sort of advantage, but it's better than moving the king to f8. If your opponent plays 12. ...Qxe7, then you can capture the queen with Bxe7, forcing the king to capture back on e7. At that point, your trap would have served its purpose: you've taken your opponent's queen, delayed their opening development, and their king can no longer castle. For you, your king is safe and you have enough minor pieces and your queen to win the game.</p>
<ol start="12">
<li>... Kf8</li>
</ol>
<p>Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769706579275/75cbb3ac-d7a3-4a9e-8d3c-10fe86f6311c.png" alt="white continues to attack the black king with the rook" class="image--center mx-auto" width="703" height="700" loading="lazy"></p>
<p>The light squared bishop has been sitting on c4 since the game started. It's finally time for it to join and support the attack.</p>
<ol start="13">
<li>Rf7+</li>
</ol>
<p>White checks the black king, forcing it back to e8. The king cannot capture the rook because it’s protected by the bishop on c4. No matter what black plays at this point, the game will end in two moves. If black plays:</p>
<ol start="13">
<li>... Kg8</li>
</ol>
<p>Then the game ends with a double check:</p>
<ol start="14">
<li>Rf8#</li>
</ol>
<p>If black plays this instead:</p>
<ol start="13">
<li>... Ke8</li>
</ol>
<p>Then white can respond with a check, forcing the game to end:</p>
<ol start="14">
<li><p>Qe1+ Qe7</p>
</li>
<li><p>Qxe7#</p>
</li>
</ol>
<p>This game showed how placing your pieces on certain squares can help you gain an advantage later in the game. For example, white's light squared bishop seemed insignificant until it was needed to end the game. Placing the bishop on c4 is where the Italian Game starts and that bishop can become very troublesome for your opponents if they don't defend properly.</p>
<p>Here's a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707180969/2558a06d-ae2f-4c63-a4c1-d51fe8364f46.gif" alt="replay of the moves from the Giuoco Piano variation of the Italian Game" class="image--center mx-auto" width="704" height="704" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>c3 Nf6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>cxd4 Bb4+</p>
</li>
<li><p>Nc3 Nxe4</p>
</li>
<li><p>O-O Nxc3</p>
</li>
<li><p>bxc3 Bxc3</p>
</li>
<li><p>Ba3 Bxa1</p>
</li>
<li><p>Re1+ Ne7</p>
</li>
<li><p>Rxe7+ Kf8</p>
</li>
<li><p>Rxf7+ Ke8</p>
</li>
<li><p>Qe1+ Qe7</p>
</li>
<li><p>Qxe7#</p>
</li>
</ol>
<h2 id="heading-game-2">Game #2</h2>
<p>Here's our starting position again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707790507/938b0635-36a0-4479-a351-939c7c1a97a2.png" alt="Italian Game starting position" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>Nc3 Nf6</p>
</li>
<li><p>d3 d6</p>
</li>
<li><p>Bg5</p>
</li>
</ol>
<p>Nothing much has happened here. Both sides have focused on developing their pieces so far and the game is still balanced. Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707804625/2f5803a7-3e14-412e-bc45-4312a43d4768.png" alt="white pin on black knight" class="image--center mx-auto" width="700" height="705" loading="lazy"></p>
<p>The common move here for black is usually h6, and that is probably the best move. Most players don’t want to worry about the bishop pin when they want to move the queen or the f6-knight, so it's usually a good idea for them to start pushing the bishop away.</p>
<ol start="6">
<li><p>... h6</p>
</li>
<li><p>Bf6</p>
</li>
</ol>
<p>With this move, white forces the black queen to capture on f6:</p>
<ol start="7">
<li>... Qxf6</li>
</ol>
<p>Now white can start setting a trap. Here's the current position of the board:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707816779/5b323bd9-83a0-4871-8039-c71bb92edf5a.png" alt="black queen captures on f6" class="image--center mx-auto" width="705" height="703" loading="lazy"></p>
<ol start="8">
<li>Nd5</li>
</ol>
<p>This forces the queen back to d8. If the queen moves to e6, it'll be forked with 9. Nc7+. If the queen moves to g6 in order to put pressure on the kingside, the knight can fork the king and rook on c7 as well. So the best move for white would be moving back to d8.</p>
<ol start="8">
<li><p>... Qd8</p>
</li>
<li><p>c3</p>
</li>
</ol>
<p>Now white is trying to take more control of the center.</p>
<ol start="9">
<li>... Be6</li>
</ol>
<p>Black attempts to add pressure in the center while developing a minor piece. But this move allows white to move on with some traps. It’s not very evident to see with the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707831082/b7db3201-f3a7-4497-9d2e-9d3970b0a644.png" alt="black bishop to e6" class="image--center mx-auto" width="700" height="702" loading="lazy"></p>
<ol start="10">
<li><p>d4 exd4</p>
</li>
<li><p>cxd4</p>
</li>
</ol>
<p>Black can play a couple of moves here, but none of them really leads to an advantage. If black plays 11. ...Bb4+, then you'd have something like 12. Nxb4 Bxc4 13. Nxc6 bxc6 14. Qc2 Be6 15. Qxc6+ Bd7 16. Qc3. White comes out of the situation with more control of the center and a pawn up. This is the safest route for black. The alternatives, as you'll see in the following moves, will lead to black losing at least one minor piece.</p>
<p>Here's our current position (we'll revert back to this position to see other variations for the traps later):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707840872/cdd115f6-6151-475c-bc4a-c45c38c7063f.png" alt="pawn trades in the center" class="image--center mx-auto" width="702" height="702" loading="lazy"></p>
<h3 id="heading-variation-1">Variation #1</h3>
<ol start="11">
<li>... Bb6</li>
</ol>
<p>The bishop retreats to avoid getting captured by the d4-pawn, but this is a blunder.</p>
<ol start="12">
<li>Nxb6</li>
</ol>
<p>Now black is down a piece. If black plays Bxc4, then the b6-knight will simply capture on c4. So black is forced to take the b6-knight. The reality is that, no matter what black plays in this position, it's going to be down by at least one minor piece.</p>
<ol start="12">
<li><p>... axb6</p>
</li>
<li><p>d5</p>
</li>
</ol>
<p>Here's our current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707853318/1c22380f-4306-45b2-8179-689eeffd18c2.png" alt="pawn fork on d5" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>If black chooses to move either the knight or bishop away from the pawn fork, then it'll lose the other. But the knight can attack on a5, right? Well, let's see how that pans out for black.</p>
<ol start="13">
<li><p>... Na5</p>
</li>
<li><p>Bd3</p>
</li>
</ol>
<p>Now, can black safely move the bishop away and save both pieces that were under threat? Unfortunately, the knight is now trapped. So, right from when the pawn fork happened, one piece was "destined" to leave the board.</p>
<ol start="14">
<li><p>... Bg4</p>
</li>
<li><p>b4</p>
</li>
</ol>
<p>Now, no matter what black plays next, the a5-knight will be captured. Here's the position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769707864251/3b15aaeb-a9dd-458f-8a74-2dbb82a28c9b.png" alt="pawn move to trap a5-knight" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>That concludes things for this variation of the trap. Here's a replay of the first variation of the trap and the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708076475/433a2257-e556-4223-8f5d-6ed7cc964233.gif" alt="replay of moves" class="image--center mx-auto" width="702" height="700" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>Nc3 Nf6</p>
</li>
<li><p>d3 d6</p>
</li>
<li><p>Bg5 h6</p>
</li>
<li><p>Bxf6 Qxf6</p>
</li>
<li><p>Nd5 Qd8</p>
</li>
<li><p>c3 Be6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>cxd4 Bb6</p>
</li>
<li><p>Nxb6 axb6</p>
</li>
<li><p>d5 Na5Bd3 Bg4</p>
</li>
<li><p>b4</p>
</li>
</ol>
<h3 id="heading-variation-2">Variation #2</h3>
<p>Now, let's go back to the position that started the first variation:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708094266/23380687-0b20-477c-8b42-1b5e262742a9.png" alt="variation 2 starting position " class="image--center mx-auto" width="702" height="702" loading="lazy"></p>
<p>If black decides to capture the d5-knight, here's what will happen:</p>
<ol start="11">
<li><p>... Bxd5</p>
</li>
<li><p>exd5</p>
</li>
</ol>
<p>Which brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708101452/7e73753f-d97d-4935-a5a5-a79e5748c47e.png" alt="pawn attack on black knight and bishop" class="image--center mx-auto" width="702" height="703" loading="lazy"></p>
<p>Two of white's minor pieces are now under attack and one will eventually be captured. If black plays:</p>
<ol start="12">
<li>... Bb4+</li>
</ol>
<p>Then you'll have something like this:</p>
<ol start="13">
<li><p>Kf1 Ne7</p>
</li>
<li><p>Qa4+ Qd7</p>
</li>
<li><p>Qxb4</p>
</li>
</ol>
<p>Black ends up losing the bishop. Here's a replay of the moves above, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708118695/968de982-1687-42d1-80cb-8bc11a7d4c7d.gif" alt="replay of moves" class="image--center mx-auto" width="702" height="704" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>Nc3 Nf6</p>
</li>
<li><p>d3 d6</p>
</li>
<li><p>Bg5 h6</p>
</li>
<li><p>Bxf6 Qxf6</p>
</li>
<li><p>Nd5 Qd8</p>
</li>
<li><p>c3 Be6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>cxd4 Bxd5</p>
</li>
<li><p>exd5 Bb4+</p>
</li>
<li><p>Kf1 Ne7</p>
</li>
<li><p>Qa4+ Qd7</p>
</li>
<li><p>Qxb4</p>
</li>
</ol>
<h2 id="heading-game-3-legals-mate">Game #3 – Legal's Mate</h2>
<p>The Legal Trap is one that allows you to capitalize on your opponent's mistakes in the opening phase of the game. With this trap, the game ends after eight moves.</p>
<p>Note that the trap may not work against intermediate players. Most of the moves that lead up to the mate are all bad moves and you won’t often see that many bad moves in row.</p>
<p>As usual, here's the starting position of the Italian Game:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708141459/53fda81e-abb8-42a6-9950-9ea8c0d7a2f3.png" alt="Italian Game starting position" class="image--center mx-auto" width="703" height="705" loading="lazy"></p>
<ol start="3">
<li>... d6</li>
</ol>
<p>This is black's first bad move. The d6-pawn now prevents the development of the dark squared bishop. Beginners often make this mistake because they want to strengthen the support on the e-pawn and use the light squared bishop to pin white's knight.</p>
<ol start="4">
<li>Nc3 Bg4</li>
</ol>
<p>Here's the position so far:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708149205/b654c08e-0495-48e2-bf46-e8a69b72434d.png" alt="black bishop pin on white knight" class="image--center mx-auto" width="700" height="703" loading="lazy"></p>
<p>Black pins the white knight and can decide to put more pressure by bringing the knight to d4 next.</p>
<ol start="5">
<li>h3</li>
</ol>
<p>White attempts to push the bishop back. In this position, moving the bishop back to e6 would be best for black. But most beginners would want to maintain the pin on the knight.</p>
<ol start="5">
<li>... Bh5</li>
</ol>
<p>Black moves back but continues pinning the knight. This is where white attempts to end the game by giving up the queen.</p>
<ol start="6">
<li>Nxe5</li>
</ol>
<p>Here's the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708162656/72298e75-4691-49d4-8b0e-88c0e5d7540c.png" alt="knight captures to trick black " class="image--center mx-auto" width="700" height="703" loading="lazy"></p>
<ol start="6">
<li>... Bxd1</li>
</ol>
<p>Black goes for the queen without seeing white's plan.</p>
<ol start="7">
<li><p>Bxf7+ Ke7</p>
</li>
<li><p>Nd5#</p>
</li>
</ol>
<p>The game ends in eight moves.</p>
<p>This is not a checkmate pattern you'll see often, but it's important to understand how it works. Positions like this can appear at any time, so you should focus more on understanding why the pieces were moved to certain squares instead of memorizing the lines.</p>
<p>I know I’ve mentioned this before, but it's crucial to repeat it here because if you try to use the Legal's Mate as your main strategy from the beginning of the game, then you'll most likely encounter difficulties.</p>
<p>Here’s a replay of the move, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708419808/d8c007c3-6f57-4346-a400-de4fe7720a34.gif" alt="replay of moves" class="image--center mx-auto" width="704" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 d6</p>
</li>
<li><p>Nc3 Bg4</p>
</li>
<li><p>h3 Bh5</p>
</li>
<li><p>Nxe5 Bxd1</p>
</li>
<li><p>Bxf7+ Ke7</p>
</li>
<li><p>Nd5#</p>
</li>
</ol>
<h2 id="heading-game-4">Game #4</h2>
<p>This particular trap is one that many beginners fall for. The aim is to allow your opponent to think they're getting a free pawn, but then they either lose the game or a minor piece.</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>c3 Nf6</p>
</li>
<li><p>d4 Bb6</p>
</li>
</ol>
<p>In this case, black decides not to capture the d-pawn. That move gives white an advantage in the opening, because it can start attacking with the pawns in the center. Here's the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708465419/1ef4b005-7472-4d27-805a-c8f958b03471.png" alt="black bishop moves away from center and avoids trading pawns" class="image--center mx-auto" width="703" height="700" loading="lazy"></p>
<ol start="6">
<li>dxe5</li>
</ol>
<p>This move is where most beginner players mess up. They assume that the e4-pawn is up for grabs. The moment black captures that pawn, then the knight will be trapped. But it's not just that. Here:</p>
<ol start="6">
<li><p>... Nxe4</p>
</li>
<li><p>Qd5</p>
</li>
</ol>
<p>The queen move threatens a checkmate on f7 if black tries to saves the knight. There is really nowhere for that knight to go, so you're better off saving your king with 7. ...Qe7 if you're playing as black in this position.</p>
<p>Here's a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708534985/b66970f3-6280-4b70-a166-d58e17e28686.gif" alt="replay of moves" class="image--center mx-auto" width="702" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Bc5</p>
</li>
<li><p>c3 Nf6</p>
</li>
<li><p>d4 Bb6</p>
</li>
<li><p>dxe5 Nxe4</p>
</li>
<li><p>Qd5</p>
</li>
</ol>
<h2 id="heading-game-5-the-fried-liver-attack">Game #5 - The Fried Liver Attack</h2>
<p>The Fried Liver Attack is one of the most common tricks played by beginners. Many amateur players fall for this trick because it creates tension at the beginning of the game.</p>
<p>Here's what the position of the Fried Liver Attack looks like:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Nf6</p>
</li>
<li><p>Ng5</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769711722677/8cb76159-5d2a-4a3e-bf11-6ca30b2ed342.png" alt="The Fried Liver Attack starting position" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>The most commonly played move here is d5. If you play anything else as black, then 5. Nxf7 will fork the queen and the rook.</p>
<ol start="4">
<li>… d5</li>
</ol>
<p>And we have this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769711999847/32a07dab-7592-43dd-8dd2-116fdf55fbde.png" alt="black plays d5 to block the white bishop" class="image--center mx-auto" width="703" height="706" loading="lazy"></p>
<ol start="5">
<li>exd5 Nxd5</li>
</ol>
<p>The 5. …Nxd5 play is one I wouldn’t recommend for most beginners playing as black. It can lead to some complicated situations.</p>
<ol start="6">
<li>Nxf7</li>
</ol>
<p>Now black has no option other than to capture the f7-knight, which now prevents the king from castling later in the game. If black ignores the knight, then it’ll lose either its queen or rook.</p>
<ol start="6">
<li><p>… Kxf7</p>
</li>
<li><p>Qf3+</p>
</li>
</ol>
<p>The problem now is that the king is being forced to move closer to the center of the board and protect the knight on d5. Remember, one of the opening principles in chess is to castle your king early, but black can no longer do that.</p>
<p>If black decides to move the king backwards, let’s say 7. …Kg8, then the game will end in three moves: Bxd5+ Qxd5 9. Qxd5+ Be6 10. Qxe6#. If black moves to e8 instead, then white can capture the knight on d5 and black still wouldn’t be able to castle.</p>
<ol start="7">
<li>… Ke6</li>
</ol>
<p>This is not a completely losing position for black, but it’ll be easier for white to put more pressure on the king, and if black doesn’t play very well, the game could end. With the king in the center, white can add more pieces to the attack:</p>
<ol start="8">
<li>Nc3</li>
</ol>
<p>The knight now threatens the black knight as well.</p>
<ol start="8">
<li><p>… Nb4</p>
</li>
<li><p>O-O c6</p>
</li>
</ol>
<p>Here’s the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769712632064/0ed2c8a4-14e5-4eaf-96ff-bbed68b5c0cc.png" alt="black plays c6 to add support for the d5-knight " class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>As you can see, white has more advantage: the black king can no longer castle and is close to the center of the board. The white king has castled and is safe, and white can focus on developing its pieces while black has to find a way to prevent a checkmate or losing the knights.</p>
<p>It’s still possible for black to win in the situation, but this can become very complicated, especially for beginners.</p>
<p>Here’s a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769712918353/338cc754-d89f-483f-b737-9b1799246db4.gif" alt="replay of moves" class="image--center mx-auto" width="700" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Nf6</p>
</li>
<li><p>Ng5 d5</p>
</li>
<li><p>exd5 Nxd5</p>
</li>
<li><p>Nxf7 Kxf7</p>
</li>
<li><p>Qf3+ Ke6</p>
</li>
<li><p>Nc3 Nb4</p>
</li>
<li><p>O-O c6</p>
</li>
</ol>
<h2 id="heading-game-6-anti-fried-liver-defence">Game #6 - Anti-Fried Liver Defence</h2>
<p>From our last game, here’s the setup for the Fried Liver Attack:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 Nf6</p>
</li>
<li><p>Ng5</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708545356/008d3b15-a358-4a97-9821-65b8fe58f476.png" alt="Fried Liver Attack starting position" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<p>Since many beginners struggle with the tension created from the Fried Liver Attack, they try to avoid it completely from the beginning of the game. So, some might play h6 as their third move to prevent the white knight from moving to the g5 square. That is:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 h6</p>
</li>
</ol>
<p>Which leads to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708558473/40a79404-2603-4971-bf91-b4d51ec6267d.png" alt="Anti-Fried Liver Defence starting position " class="image--center mx-auto" width="705" height="705" loading="lazy"></p>
<ol start="4">
<li><p>d4 exd4</p>
</li>
<li><p>Nxd4</p>
</li>
</ol>
<p>This is where white sets the trap. Black should continue developing minor pieces and castle the king. A move like 5. ...Nf6 would work for black. But some people may want to double the attack on the d4-knight in order to push it back:</p>
<ol start="5">
<li>... Bc5</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708561048/356f3282-5210-4c20-8598-2f1ef7dfe21a.png" alt="black blunders by moving the bishop to c5" class="image--center mx-auto" width="703" height="703" loading="lazy"></p>
<ol start="6">
<li><p>Bxf7+ Kxf7</p>
</li>
<li><p>Qh5+ Kf8</p>
</li>
<li><p>Qxc5+</p>
</li>
</ol>
<p>With these moves, black no longer has the option of castling and the kingside looks weaker.</p>
<p>Here's a replay and the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769708627936/3c6f0fe1-f918-4d3d-a75a-fceaf35a26aa.gif" alt="replay of moves" class="image--center mx-auto" width="704" height="702" loading="lazy"></p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bc4 h6</p>
</li>
<li><p>d4 exd4</p>
</li>
<li><p>Nxd4 Bc5</p>
</li>
<li><p>Bxf7+ Kxf7</p>
</li>
<li><p>Qh5+ Kf8</p>
</li>
<li><p>Qxc5+</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This handbook showed you some of the most common beginner traps for the Italian Game. Although we saw most of the traps from the perspective of white, it can also help you defend against them when playing as black.</p>
<p>Opening moves in chess can be quite tricky. You may decide to stick with opening principles by developing your pieces, trying to control the center, and castling early. But, along the way, you may miss obvious mistakes and fall for your opponent’s traps.</p>
<p>You shouldn’t learn chess openings in order to replicate everything you see in various courses. Instead, you should try and understand why certain moves were made and their outcome. That way, you can improve your tactics and strategy and be able to recognize similar positions in other games.</p>
<p>I hope this handbook has been helpful for you on your chess journey. You can <a target="_blank" href="https://lichess.org/@/IHECHIKARA">find me on Lichess @ IHECHIKARA</a>.</p>
<p>You can watch the video version of this handbook here.</p>
<p>You can <a target="_blank" href="https://www.freecodecamp.org/news/checkmate-patterns-in-chess-for-beginners/">learn about checkmate patterns in chess here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Checkmate Patterns in Chess for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ After learning the rules and basics of chess, there are various concepts that beginners should learn in order to keep improving. Some of these concepts include opening principles, middle game concepts, endgame fundamentals, and strategy. In this hand... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/checkmate-patterns-in-chess-for-beginners/</link>
                <guid isPermaLink="false">68a72ee03bbf12346853dce9</guid>
                
                    <category>
                        <![CDATA[ chess ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Strategy ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 21 Aug 2025 14:36:16 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755720597720/2bb80910-7697-45e2-8163-dbfb73b4998f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>After learning the rules and basics of chess, there are various concepts that beginners should learn in order to keep improving. Some of these concepts include opening principles, middle game concepts, endgame fundamentals, and strategy.</p>
<p>In this handbook, we’ll focus on endgame fundamentals. You’ll learn about some common checkmate patterns for beginners and how you can recognize these patterns more easily to increase your chances of winning.</p>
<p>This handbook is not for absolute beginners. You should understand these concepts before proceeding:</p>
<ul>
<li><p>How to identify each chess piece.</p>
</li>
<li><p>How to set up a chess board.</p>
</li>
<li><p>How each piece moves.</p>
</li>
<li><p>Some basic chess terms like "capture", "castling", "check", "checkmate", "piece promotion", "fork", "pin", and so on.</p>
</li>
</ul>
<p>If you're new to chess, or you're not yet familiar with the prerequisites, then <a target="_blank" href="https://lichess.org/learn">this free resource</a> is a good place to start.</p>
<p>In the first chapter, you'll learn about algebraic chess notations. You’ll learn about files and ranks, how to identify and denote each square on a board, and how to record chess moves using algebraic chess notations.</p>
<p>In the second chapter, you’ll learn about some checkmate patterns like queen and king vs king, two rooks vs king, opera mate, Anastasia’s mate, and so on.</p>
<p>I've provided some exercises in different sections to help you practice. You can find the answers to each exercise at the end of the handbook.</p>
<p>I’ve also included some practice positions for each endgame pattern. To use them, click on the link provided for each exercise, then click on “CONTINUE FROM HERE” in the options at the bottom-right of the page. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755630305311/3fdcec2a-a6b2-485b-9e78-1a1620d522a0.jpeg" alt="press the &quot;CONTINUE FROM HERE&quot; button to practice the position against an engine" class="image--center mx-auto" width="971" height="816" loading="lazy"></p>
<p>This will let you practice the positions against an engine. The engine has varying levels of strength, so you should try beating each level. You can find links for all the practice positions at the end of the article. You can also use the board editor from the links to set up your own positions.</p>
<p>You can watch the video version of this handbook here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1AX7_aPWmbE" 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-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-how-to-use-this-handbook">How to Use this Handbook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-1-what-are-notations-in-chess-algebraic-chess-notation-explained">Chapter 1: What are Notations in Chess? Algebraic Chess Notation Explained</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-chess-notations">What are Chess Notations?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-algebraic-chess-notation">What is Algebraic Chess Notation?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-chess-notations-used-for">What are Chess Notations Used For?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-write-algebraic-chess-notations">How to Write Algebraic Chess Notations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-identify-squares-on-a-chess-board">How to Identify Squares on a Chess Board</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-chapter-2-checkmate-patterns-for-beginners">Chapter 2: Checkmate Patterns for Beginners</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-check-and-checkmate-in-chess">What is a Check and Checkmate in Chess?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-checkmate-patterns">Checkmate Patterns</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-checkmate-patterns-ii">Checkmate Patterns II</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-answers">Exercise Answers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practice-position-urls">Practice Position URLs</a></p>
</li>
</ol>
<h2 id="heading-how-to-use-this-handbook"><strong>How to Use this Handbook</strong></h2>
<p>This handbook is not meant to be read and understood just once. If you're a beginner, then chances are high that you'll reference it multiple times in order to understand certain concepts.</p>
<p>In order to get the best out of this resource, you'll need a chess board. You can use either a physical board or an online chessboard. I recommend using <a target="_blank" href="https://lichess.org/">Lichess</a> if you're going to use the latter option.</p>
<p>You should try and replicate the moves as you read. Remember, you're not meant to understand everything the first time you read it, so it’s totally fine to go over one concept again and again.</p>
<p>Chess books can be boring, but don't let that hinder your progress. It gets interesting when you're able to understand, practice, and see improvements from what you've learned.</p>
<p>Let's get started!</p>
<h2 id="heading-chapter-1-what-are-notations-in-chess-algebraic-chess-notation-explained">Chapter 1: What are Notations in Chess? Algebraic Chess Notation Explained</h2>
<p>You can use chess notations to record chess moves, and this handbook will rely heavily on them to teach you difference concepts about chess as a beginner. The first time you learn about writing or reading notations may seem overwhelming, but don't worry – with constant practice and studying, you'll get the hang of it.</p>
<h3 id="heading-what-are-chess-notations"><strong>What are Chess Notations?</strong></h3>
<p>To put it simply, chess notation is a method of recording moves in a chess game. In a physical chess game, it usually involves two players writing down moves as they’re played.</p>
<p>While there are other forms of chess notations like descriptive, coordinate, numeric, and so on, we'll focus primarily on algebraic chess notation.</p>
<h3 id="heading-what-is-algebraic-chess-notation"><strong>What is Algebraic Chess Notation?</strong></h3>
<p>Algebraic chess notation is the standard way of recording chess. Each notation shows the move number, the piece moved, and the position of the board where the piece was moved to. In some cases, the notations also show an action being performed, like a check, a checkmate, castling, and so on.</p>
<p>For example:</p>
<ol>
<li><p>e4 d5</p>
</li>
<li><p>d4 dxe4</p>
</li>
<li><p>Nc3 e6</p>
</li>
</ol>
<p>These may look strange if it's your first time looking at notations. But don't worry, you'll understand how to write and read/interpret them as we progress.</p>
<p>In online games, they're recorded automatically:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278278381/25c66717-56a0-46ac-99dd-5db78c6b1a37.png" alt="chess notations on Lichess" class="image--center mx-auto" width="2510" height="1291" loading="lazy"></p>
<p>The image above shows a chess game played on <a target="_blank" href="https://lichess.org/">lichess.org</a>. On the right side of the image, you can see the notations of the game as each move was played, along with numbers corresponding with the moves. We'll talk more about the numbers later.</p>
<p>Now that you know what notations are, let's talk about why they're needed.</p>
<h3 id="heading-what-are-chess-notations-used-for"><strong>What are Chess Notations Used For?</strong></h3>
<p>Here are some of the uses of chess notations:</p>
<h4 id="heading-competitiveprofessional-chess">Competitive/Professional Chess</h4>
<p>Algebraic chess notation is the standard way of recording a chess game in tournaments. In over the board tournaments, each player is given a piece of paper with columns for writing each move played. Note that this involves recording their opponent's moves as well.</p>
<h4 id="heading-studying-and-teaching-chess">Studying and Teaching Chess</h4>
<p>You can think of chess notations as the language of chess, and to learn about something, there has to be a way to pass and communicate information.</p>
<h4 id="heading-communication">Communication</h4>
<p>With chess notations, you can communicate moves and share games with players across the world without needing a physical board.</p>
<h3 id="heading-how-to-write-algebraic-chess-notations"><strong>How to Write Algebraic Chess Notations</strong></h3>
<p>Algebraic chess notation makes use of the board coordinates and the pieces to denote moves.</p>
<p>Let's start with the coordinates:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278306647/e0c0d1d4-74cb-4f49-9180-42b81102f7d2.png" alt="an empty chess board" class="image--center mx-auto" width="1093" height="1096" loading="lazy"></p>
<p>The image above shows a chess board without the pieces. On the right edge of the board are numbers 1 to 8, and the bottom edge of the board has letters a to h. You can use these numbers and letters to refer to a particular position of the board.</p>
<p>Each vertical column (top to bottom) in a chess board is called a file, while each horizontal row (left to right) is called a rank. You can also associate them with the letters and numbers: the letters can be used to reference files, while the numbers can be used to reference ranks.</p>
<h4 id="heading-files-a-to-f">Files a to f</h4>
<p>There are eight files in a chess board. Another way to say this is that, from top to bottom, there are eight vertical lines (stack of squares from top to bottom) in a chess board. Each vertical line is associated with a letter, which is usually written at the bottom edge of the board. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278341256/ee7fae5e-3a9d-4477-b036-dbcaa031b92d.png" alt="a chess board show an arrow on each file" class="image--center mx-auto" width="1098" height="1096" loading="lazy"></p>
<p>To help you understand files, let's try and identify some of them separately. The image below shows the a-file:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278367782/da2fab28-9cc3-47a8-ad90-cad1e55cfbb7.png" alt="a chess board with an arrow on the a-file" class="image--center mx-auto" width="1087" height="1087" loading="lazy"></p>
<p>We can tell that this is the a-file because the all the squares in that vertical column fall under the part of the board labelled "a". Remember that files go from top to bottom.</p>
<p>Here's another example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278386430/f2842bda-1dee-466e-9ddb-70328001873c.png" alt="a chess board with an arrow on the f-file" class="image--center mx-auto" width="1093" height="1092" loading="lazy"></p>
<p>This arrow runs from top to bottom, but on a different part of the board. To know what file this is, simply look the the letter associated with the vertical column. Using that, we can say that the arrow is on the the f-file.</p>
<p>Here's an exercise for you (you can find the answers to each exercise at the end of the handbook):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278412195/1f83d8b6-d192-4f60-9604-5a8de609ceec.png" alt="an exercise to find what file the arrow is on" class="image--center mx-auto" width="1093" height="1087" loading="lazy"></p>
<p>In the image above, using the letters on the board, what file is the arrow on?</p>
<h4 id="heading-ranks-1-to-8">Ranks 1 to 8</h4>
<p>Just like files, we have eight ranks in a chess board. These are the eight horizontal lines (stack of squares from left to right) in a chess board. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278462326/7308dc99-8679-40f9-bd98-02a7644ba14a.png" alt="a chessboard with an arrow on each rank" class="image--center mx-auto" width="1089" height="1090" loading="lazy"></p>
<p>Let's identify some of the ranks separately.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278544960/1e785b64-dc0a-4770-a70c-95e9bdfd4a06.png" alt="a chessboard with an arrow on the fourth rank" class="image--center mx-auto" width="1087" height="1087" loading="lazy"></p>
<p>Using the position of the arrow, you can tell the rank. The arrow run from left to right on the part of the board with the number 4, so we can say that it is on the fourth rank.</p>
<p>Here's another example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278560474/1b75018e-2197-4d7f-8614-add51e756024.png" alt="a chessboard with an arrow on the first rank" class="image--center mx-auto" width="1087" height="1080" loading="lazy"></p>
<p>You may confuse files and ranks here since you can see the letters at the bottom. Remember, we're dealing with ranks here, and they go from left to right, not top to bottom. From left to right, in the image above, we can see the letter 1. So the arrow is on the first rank.</p>
<p>Here's an exercise for you:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278592936/77305a72-bbc8-45f9-aff4-82a9cbb8f9de.png" alt="a chessboard with an arrow on the eighth rank" class="image--center mx-auto" width="1089" height="1086" loading="lazy"></p>
<p>In the image above, using the numbers on the board, what rank is the arrow on?</p>
<h3 id="heading-how-to-identify-squares-on-a-chess-board">How to Identify Squares on a Chess Board</h3>
<p>Now that you know what files and ranks are in chess, let's see how you can use them to identify a square. Identifying a square is important when writing notations. Each notation is made up of the move number, the piece moved, and the coordinate. In the case, a coordinate is the combination of a file and a rank.</p>
<p>Let's start with this image:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278624546/a25a44db-7950-462b-ac2d-24c6105743f6.png" alt="a chessboard with a circle on e5" class="image--center mx-auto" width="1093" height="1084" loading="lazy"></p>
<p>In the image above, we have a circle on a random square. The goal here is to identify that square, that is, to refer to it as "something".</p>
<p>To identify the square, you have to trace its file and the rank. Let' start with the file.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278670477/1e0355a5-35f7-4098-adba-0ab1b7fb5980.png" alt="a chessboard with a circle and arrow pointing to e5" class="image--center mx-auto" width="1090" height="1084" loading="lazy"></p>
<p>Using the arrow, we can see that the circle falls under the e-file. Next, let's trace the rank.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278713838/05fe7d3c-0902-4b85-b7f9-270b9475146b.png" alt="a chessboard with a circle and arrows pointing to e5" class="image--center mx-auto" width="1089" height="1086" loading="lazy"></p>
<p>Great! We can tell that the circle is on the fifth rank.</p>
<p>So we can say that we have a circle on the e-file and the fifth rank. Using notations, you can write it as e5.</p>
<p>In the next example, we'll identify the position of chess pieces. In order to do that, you need to know the letters that represent each piece on a board:</p>
<p>King = K</p>
<p>Queen = Q</p>
<p>Rook = R</p>
<p>Bishop = B</p>
<p>Knight = N</p>
<p>Pawn = no letter (denoted by the square they move to).</p>
<p>In our last example, we identified the square as e5. If you replace that square with a chess piece, then the the notation would start with the letter of that piece, followed by its position on the board. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278735253/f4b13367-7bbe-48f9-b7e3-f8359081cbe0.png" alt="queen on e5" class="image--center mx-auto" width="1087" height="1086" loading="lazy"></p>
<p>Now we have the queen on the e5 square. The notation will look like this: Qe5. This way of writing the letter of the piece, followed by the coordinate of the square applies to other pieces, except the pawns. For pawns, you only write the coordinate.</p>
<p>If you had a rook on e5, the notation would be Re5, Ke5 for a king, Ne5 for a knight, Be5 for a bishop, and e5 for a pawn.</p>
<h3 id="heading-how-to-write-algebraic-chess-notations-1"><strong>How to Write Algebraic Chess Notations</strong></h3>
<p>We stated earlier that algebraic chess notations show the move number, the piece moved, and the position of the board where the piece is moved to. In our examples, you've seen how to write the piece moved, and where it was moved to using coordinate (files and ranks). In the examples for this section, we'll add the move number to complete the algebraic chess notation.</p>
<p>By move number, we simply mean the turn count. Each move number is associated with one White and one Black move. For instance, the first move of the game will have a move number of 1. Let's look at some examples.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278762190/45bcd65e-3901-40b0-a602-494bfc696643.png" alt="chessboard starting position" class="image--center mx-auto" width="1132" height="1123" loading="lazy"></p>
<p>Each piece on the board is in its starting position. Let's make the first move for White:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278784164/52dc3f3b-16eb-47ef-b157-2d1bef6f0564.png" alt="first pawn move for white" class="image--center mx-auto" width="1129" height="1120" loading="lazy"></p>
<p>White has moved a pawn to e4. To record this, you'd start with the move number, followed by the piece and coordinate. That is:</p>
<ol>
<li>e4</li>
</ol>
<p>Next, Black's move.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278805904/2c4632a4-74cb-45df-9c4e-b7c9553c1700.png" alt="first pawn move for black" class="image--center mx-auto" width="1123" height="1122" loading="lazy"></p>
<p>Black responded by moving a pawn to e4. Since this is Black's first move, it'll also be recorded under move number 1:</p>
<ol>
<li>e4 e5</li>
</ol>
<p>If you look at the algebraic notation above, you can see that both notations are written on the same line, and are both associated with move number 1. To interpret this, the first coordinate belongs to White, while the second belongs to Black.</p>
<p>To make this even clearer, let's continue the game. It's White's turn to play.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278832714/22efd090-04bb-485d-b0be-8eada8d76784.png" alt="white knight to f3" class="image--center mx-auto" width="1125" height="1120" loading="lazy"></p>
<p>The white knight was moved to f3, which can be denoted by Nf3. Since this is White's second move, it'll be recorded under move number 2:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3</p>
</li>
</ol>
<p>Now Black has to respond with a second move.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278861739/d4e8e53f-6753-4ad8-ac2d-2e44c573c63c.png" alt="black knight to c6" class="image--center mx-auto" width="1119" height="1117" loading="lazy"></p>
<p>Black played Nc6 (knight to c6). Remember that this is the second move for Black, so it has to be recorded in move number 2, right after the notation for White's second move. So we'll have this:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
</ol>
<p>This system of recording chess moves is known as algebraic chess notation. Here's a summary of how it works:</p>
<ul>
<li><p>You write the move number.</p>
</li>
<li><p>You write piece moved (omitted for pawns).</p>
</li>
<li><p>You write the coordinate (file and rank) that the piece moved to.</p>
</li>
</ul>
<p>With this information, you can easily read and write chess notations! But we're not done yet. How do you write checks, checkmates, castling, and pawn promotions?</p>
<h3 id="heading-how-to-write-a-check-notation-in-algebraic-chess-notations"><strong>How to Write a Check Notation in Algebraic Chess Notations</strong></h3>
<p>You can use the + symbol to denote a check. This comes after the move notation. That is, you write the notation as you would for any other move, and then add the + symbol at the end. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278891757/ecb8de32-58c3-481c-8fa2-e229cd555fab.png" alt="queen check" class="image--center mx-auto" width="1117" height="1116" loading="lazy"></p>
<p>Here, the queen moves to e7 to check the king. So the notation would be Qe7+. The + at the end denotes the check by the queen. If you write it as Qe7, without the check symbol, then you'd have an inaccurate notation of the move.</p>
<h3 id="heading-how-to-write-a-checkmate-notation-in-algebraic-chess-notations"><strong>How to Write a Checkmate Notation in Algebraic Chess Notations</strong></h3>
<p>A checkmate is denoted by the # symbol. It also comes after the move notation. That is, you write the notation as you would for any other move, and then add the # symbol at the end. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278908199/7a808ce3-25eb-419b-ac9f-ef03a4bcb4ef.png" alt="checkmate with two rooks" class="image--center mx-auto" width="1117" height="1116" loading="lazy"></p>
<p>In the image above, the rook moved to g8 to win the game. The notation would be Rg8#. The # symbol denotes the checkmate.</p>
<h3 id="heading-how-to-write-a-castling-notation-in-algebraic-chess-notations"><strong>How to Write a Castling Notation in Algebraic Chess Notations</strong></h3>
<p>In a chess game, castling can either be to the kingside or queenside. Kingside castling is denoted using O-O, while queenside castling is denoted using O-O-O. Note that the symbol is not a zero. Rather, it's an O, as in <strong>o</strong>range.</p>
<h3 id="heading-how-to-write-a-capture-move-in-algebraic-chess-notations"><strong>How to Write a Capture Move in Algebraic Chess Notations</strong></h3>
<p>Capture moves are denoted using the x symbol. Here are some different variations:</p>
<ul>
<li><p>Qxg6 means that the queen captured a piece on g6.</p>
</li>
<li><p>Qxg6+ means that the queen captured a piece on g6 and checked the king.</p>
</li>
<li><p>Qxg8# means that the queen captured a piece on g8 and checkmated the king.</p>
</li>
<li><p>dxe4 mean that a pawn captured a piece on e4.</p>
</li>
</ul>
<p>In a case where you have two pieces that can move to the same square, you have to include the file of the piece that was moved. Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755278931250/f8345127-37c3-4b34-aa72-67f625a7d8af.png" alt="two knights attacking a rook on g8" class="image--center mx-auto" width="1084" height="1084" loading="lazy"></p>
<p>In the board above, we have two knights: one on the f-file and another on the h-file. Both knights can capture the rook on g8, and it may be confusing for someone reading your notations if you don't specify which knight was moved.</p>
<p>To denote this, you have to add the file from where the knight was moved in your notation. So, if you capture with the knight on the f-file, you'd have Nfxg8 (knight on f-file captured a piece on g8). On the other hand, capturing with the knight on the h-file will result to a notation like this: Khxg8.</p>
<p>This is not only specific to capturing pieces. If you have two knights that can move to the same square, then you'd have to include the previous file of whichever knight that is moved. So, assuming that we didn't have a rook to capture on g8, you'd have Nfg8 to denote that the knight on f-file moved to g8, and Nhg8 to denote that the knight on the h-file moved to g8.</p>
<h3 id="heading-how-to-denote-piece-promotion-in-algebraic-chess-notations"><strong>How to Denote Piece Promotion in Algebraic Chess Notations</strong></h3>
<p>You can use the = symbol to denote the promotion of a pawn. That is:</p>
<ul>
<li><p>e8=Q means that pawn moved to e8 and got promoted to a queen.</p>
</li>
<li><p>e8=Q+ means that pawn moved to e8, got promoted to queen, and checked the king.</p>
</li>
<li><p>e8=Q# means that pawn moved to e8, got promoted to queen, and checkmated the king.</p>
</li>
<li><p>e8=N means that pawn moved to e8 and got promoted to a knight.</p>
</li>
</ul>
<p>Here are two exercises for you:</p>
<ul>
<li><p>How do you write the notation if a pawn moves to d1 and gets promoted to a rook?</p>
</li>
<li><p>How do you write the notation if a pawn moves to b8 and gets promoted to a bishop?</p>
</li>
</ul>
<p>And here's the main exercise for this chapter. Show the final board position using these notations:</p>
<ol>
<li><p>e4 e5</p>
</li>
<li><p>Nf3 Nc6</p>
</li>
<li><p>Bb5 Nf6</p>
</li>
<li><p>O-O Nxe4</p>
</li>
<li><p>Re1 Nd6</p>
</li>
<li><p>Nxe5 Be7</p>
</li>
<li><p>Bf1 Nxe5</p>
</li>
<li><p>Rxe5 O-O</p>
</li>
<li><p>d4 Bf6</p>
</li>
<li><p>Re1 Re8</p>
</li>
<li><p>c3 Rxe1</p>
</li>
<li><p>Qxe1 Nf5</p>
</li>
<li><p>Bf4 d6</p>
</li>
<li><p>a4 Qe7</p>
</li>
<li><p>Na3 g5</p>
</li>
<li><p>Bd2 Qxe1</p>
</li>
<li><p>Rxe1 Bd7</p>
</li>
<li><p>a5 Kg7</p>
</li>
</ol>
<h2 id="heading-chapter-2-checkmate-patterns-for-beginners">Chapter 2: <strong>Checkmate Patterns for Beginners</strong></h2>
<p>Before we look at the common checkmate patterns, let's talk a bit about what a check means. We'll do this using the attack pattern or capture method of the pieces.</p>
<h3 id="heading-what-is-a-check-and-checkmate-in-chess"><strong>What is a Check and Checkmate in Chess?</strong></h3>
<p>The main goal of a standard chess match is to capture your opponent's king. You can do this in multiple ways, with different combinations of pieces.</p>
<p>A check is simply an attack on a king. When the king is in check, it must move to a safe square. A safe square for a king in chess is a square where the king is not under attack.</p>
<p>This is an example of a check:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279141941/1374098d-5c8b-4440-8a4f-724743312b39.png" alt="queen check" class="image--center mx-auto" width="760" height="756" loading="lazy"></p>
<p>The king in the image above is being threatened by the queen. You can deliver checks based on how a piece moves and captures other pieces. A rook can deliver a check like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279158250/f0c4ce08-5c36-40ab-b4b5-7fe629b36c56.png" alt="rook check" class="image--center mx-auto" width="760" height="755" loading="lazy"></p>
<p>A bishop can deliver a check like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279174540/cd241bae-1c07-4ba8-a1b9-ecc732102ed3.png" alt="bishop check" class="image--center mx-auto" width="758" height="758" loading="lazy"></p>
<p>Same applies to the knights and pawns – they can check the king based on their movement and mode of attack.</p>
<p>So what is a checkmate? Well, a checkmate happens when the opponent's king has no safe squares to move to after a check. This can be the result of the king being trapped by its own pieces, the king being unable to move to another square because its opponent has control of all the possible squares it can move to, or not having any piece to block the attack on the king.</p>
<p>In this sections that follow, you'll learn about different checkmate patterns using a combination of different pieces.</p>
<h3 id="heading-checkmate-patterns"><strong>Checkmate Patterns</strong></h3>
<h4 id="heading-how-to-play-the-two-rooks-vs-king-checkmate-pattern">How to Play the Two Rooks vs King Checkmate Pattern</h4>
<p>This endgame pattern usually involves two rooks against a king. It is one of the easiest checkmate patterns, but it's also easy to get carried away as a beginner. Here, you'll learn how to effectively mate and end a game with two rooks.</p>
<p>Consider this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279449474/be39b6e4-7816-4717-b17a-534f36c7f9bd.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="763" loading="lazy"></p>
<p>White can end this game in six moves. Here are some things to keep in mind when you have a position like this:</p>
<ul>
<li><p>Restrict the opposing king's movement by cutting off squares where it can move to.</p>
</li>
<li><p>Keep your rooks away from the opposing king or/and close to each other.</p>
</li>
</ul>
<p>Let's see how each step works using the position above.</p>
<p><strong>Restrict the King:</strong></p>
<p>Looking at the initial position above, you can see that the king is on the f-file. Our goal here is to isolate the king and restrict its movement. One common move for beginners would be to check the king with Rf2+. But this allows the king to move closer to the rook on d4. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279474239/1a1b715c-09f0-4fc4-9cac-d1f47e48e746.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="757" height="760" loading="lazy"></p>
<p>While this is still a winning position, you'll spend more moves trying to restrict the king's movement. If you're playing a timed game, you may end up with a forced draw, losing a rook, or even losing the game, depending on the pieces on the board. This makes it important to know where and when to move your rooks.</p>
<p>So, back to the starting position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279507154/dfc85f37-4d5e-45fe-8246-7adb8e5cae7e.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="763" loading="lazy"></p>
<ol>
<li>Re2 Kf5.</li>
</ol>
<p>Playing Re2 cuts off the e-file, meaning that the black king can no longer get on any square in that file. Since the king can not pass through or get on the e-file, it means that the a to e files have become inaccessible to it. It is now left with the f to h files.</p>
<p>The king responds with Kf5, an attempt to get closer and capture a rook. At this point, you'd want to stay away from the king.</p>
<p><strong>Move Your Rooks Away From The King:</strong></p>
<p>This is the current position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279519416/6635d2ec-2781-48c7-823b-fe8ab3317c5a.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="757" loading="lazy"></p>
<p>Be careful not to play Re5+, confusing the d-rook for a supporting queen. This forces you into a one rook and king checkmate endgame (you'll learn about that in the next section) after Kxe5. This is a better move:</p>
<ol start="2">
<li>Rd8</li>
</ol>
<p>Which brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279554729/5938f427-2a49-47f9-9346-9ab589e8b4b3.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="760" loading="lazy"></p>
<p>This keeps your rooks far away from the black king. Since the king is limited to one square per move, it'll have a long way to go before getting close to either rook. And in the process of getting close, you can continue limiting which files it can get on.</p>
<p>The king has five possible moves here: Kf6, Kf4, Kg6, Kg5, Kg4. The only thing these moves have in common is that they lead to nowhere. But let's assume the black king has some sort of miracle to perform here.</p>
<ol start="2">
<li>... Kg6</li>
</ol>
<p>The king moving to g6 gives you the opportunity to occupy the f-file with:</p>
<ol start="3">
<li>Rf8</li>
</ol>
<p>You have the f-file, but your rook is closer to the king:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279573831/174f9c17-4caa-48aa-aad6-11eb83f5e13a.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="760" height="757" loading="lazy"></p>
<ol start="3">
<li>... Kg7</li>
</ol>
<p>The king moves closer to challenge the rook. Unfortunately, a checkmate is still inevitable. At the point, you've not only restricted the files that the king can move to, you've also lured it all the way to the seventh rank.</p>
<p><strong>Keep Your Rooks Closer to Each Other:</strong></p>
<ol start="4">
<li>Rf1</li>
</ol>
<p>With one rook on f1 and the other on e2, you're far away from the king and have both rooks closer to each other:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279765163/b4dd7a02-0356-484d-be33-9ae1b0d1353d.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="757" height="759" loading="lazy"></p>
<p>With this position, it will take the king at least four moves to get to your rooks.</p>
<ol start="4">
<li>... Kg6</li>
</ol>
<p>All that's left is to do now is keep pushing the king away from accessing other files:</p>
<ol start="5">
<li>Rg2+</li>
</ol>
<p>Checking the king with the g-rook forces it to the h-file. Since you have a rook occupying the e-file, the king can’t go there.</p>
<ol start="5">
<li><p>... Kh5</p>
</li>
<li><p>Rh1#</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279786015/3ba53269-7129-44e0-b3bd-2e994a8e9ef5.png" alt="two rooks against a king checkmate" class="image--center mx-auto" width="878" height="757" loading="lazy"></p>
<p>There are multiple ways to checkmate the king from the starting position, and in some cases, you may already have enough space to bring your rooks together and trap the king, instead of trying to restrict it to a part of the board first.</p>
<p>Consider this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279798809/e3cdade1-b363-4aef-9d45-f34f6b56143f.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="763" height="760" loading="lazy"></p>
<p>The black king is already in a bad position. If you move the b-rook to b6, the game ends after Ra7+ and Rb8#. This did not require you to restrict the king.</p>
<p>Another thing to keep in mind is that your rooks must not always be close to each other to win games like this. Here's another position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755279808479/26e2581f-b0ee-431a-8d85-ef7d86773e36.png" alt="two rooks against a king endgame" class="image--center mx-auto" width="761" height="758" loading="lazy"></p>
<p>Here, the king is already limited to only the sixth and seventh rank, and you have enough squares/space between it and the rooks to win. There’s no need to avoid the king by moving one rook to a different part of the board.</p>
<p>Playing Rh7+ forces the king into the eighth rank and Ra8# checkmates the king.</p>
<p>You'll also notice that the white king did not participate in these moves. Its contribution was staying out of the way of the rooks. In some cases, the king can be helpful in delivering a checkmate. But if it'll block your rooks from restricting an enemy king, then you should keep your king away.</p>
<p>Here's a replay of the moves, along with the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280037181/5409f0bd-e3ca-4471-b293-8f254bc07116.gif" alt="replay of all moves in two rooks against a king endgame" class="image--center mx-auto" width="758" height="758" loading="lazy"></p>
<ol>
<li><p>Re2 Kf5</p>
</li>
<li><p>Rd8 Kg6</p>
</li>
<li><p>Rf8 Kg7</p>
</li>
<li><p>Rf1 Kg6</p>
</li>
<li><p>Rg2+ Kh5</p>
</li>
<li><p>Rh1#</p>
</li>
</ol>
<p>You can replicate them on your own if you weren't doing so already, and practice with the positions provided below.</p>
<h4 id="heading-practice-position-for-two-rooks-vs-king-endgamecheckmate-pattern">Practice Position for Two Rooks vs King Endgame/Checkmate Pattern</h4>
<p>You can practice what you've learned in the last section using this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280062216/a673f5b1-a0a6-4a90-9432-c52ce3ce9109.png" alt="practice position" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>I’ve set up the position for you here: <a target="_blank" href="https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a>. Click on the link, then click on “CONTINUE FROM HERE” to practice the position against an engine.</p>
<h3 id="heading-how-to-play-the-king-and-rook-vs-king-checkmate-pattern"><strong>How to Play the King and Rook vs King Checkmate Pattern</strong></h3>
<p>Before we talk about how to win this game, you need to learn about the concept of "direct opposition". This happens when two kings are facing each other on the same file or rank, with exactly one square between them. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280143703/c5eae79f-8e20-40a0-847b-d63f3566d361.png" alt="kings in direct opposition " class="image--center mx-auto" width="760" height="762" loading="lazy"></p>
<p>The kings in the image above are facing each other, have one square between them, and are both on the d-file. Both kings are in direct opposition.</p>
<p>Here's another example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280152482/04514349-1f19-4c7b-a2be-e1fce2e74a7b.png" alt="kings in direct opposition " class="image--center mx-auto" width="757" height="758" loading="lazy"></p>
<p>The kings are still facing each other, they also have a square between them, but are now on the seventh rank. There are other forms of opposition like the diagonal and distant opposition, but we won't discuss them here.</p>
<p>So why does direct opposition matter in our current position? Well, let's look at how the king moves.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280163774/098b5c89-946c-4483-9ad6-efb6fe018730.png" alt="all possible king moves" class="image--center mx-auto" width="759" height="759" loading="lazy"></p>
<p>The black king, in the image above, can move to all the squares with a circle on them. Now, here's what happens when the king is in direct opposition with the other king.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280176802/87880756-f232-46db-a978-c415032eec8c.png" alt="all possible king moves when in direct opposition " class="image--center mx-auto" width="758" height="757" loading="lazy"></p>
<p>Now the black king has lost the ability to move to three squares in the direction of the opposition. This also implies that the black king, using the position in the image above, no longer has access to the fourth rank. So playing Ra5+ forces the black king to move to the sixth rank, restricting it, and allowing the white king to come closer and set up another direct opposition.</p>
<p>This is one way of winning with a rook and a king. An alternative method is the box method, which we'll look at later in this section. Both techniques can be used together, but I think it would be helpful to learn them separately at first.</p>
<h4 id="heading-how-to-use-the-direct-opposition-to-win-with-a-rook-and-a-king">How to Use the Direct Opposition to Win with a Rook and a King</h4>
<p>Here's our starting position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280196692/c088d0a3-fdcb-4156-8cdb-359661d32b3e.png" alt="rook and king vs king" class="image--center mx-auto" width="760" height="760" loading="lazy"></p>
<ol>
<li>Rb5+</li>
</ol>
<p>Forcing the black king to the sixth rank.</p>
<ol>
<li>... Kd6</li>
</ol>
<p>Now the king is trying to get closer and attack your rook, so you have to bring your own king closer for support.</p>
<ol start="2">
<li>Kd4 Ke6</li>
</ol>
<p>Creating direct opposition. If the black king moves backwards (seventh rank), it loses the opportunity to pass through or be on the sixth rank. If it moves to c6, it'll have fewer squares to work with. So the best move for the black king would be Ke6.</p>
<p>Now we'll use something called the box method - a technique used when playing with a rook and a king to shrink the space where the opposing king can move in. This is the current position of the game:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280211256/8cfe2105-00b6-48cb-a630-07dd70708c64.png" alt="rook and king vs king" class="image--center mx-auto" width="763" height="757" loading="lazy"></p>
<ol start="3">
<li>Rd5</li>
</ol>
<p>This move blocks the black king from moving to the d-file and forces it into a box that will gradually shrink if you make the right moves. Here:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280223698/21ddcb13-a973-4e0b-a230-e61d12b5b52c.png" alt="rook and king vs king" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>The image above shows squares where the black king has been trapped in. The best move for the black king would be Kf6. Playing Ke7 or Kf7 would allow the white king to move closer. Remember, this is a lost position for black, but if you play against an opponent who wants to rely on luck to force a draw through a stalemate or timeout, then knowing exactly where to move your rook becomes very important.</p>
<p>Also, checks with the rook will do you no good in this position. If you check the king with Re5+, then the king will just escape to the d-file. So when you're this close to the opposing king:</p>
<ol start="3">
<li><p>... Kf6</p>
</li>
<li><p>Re5 Kf7</p>
</li>
<li><p>Kd5 Kf6</p>
</li>
</ol>
<p>The black king has gotten closer to your rook again. If you check it, it escapes through the fifth rank. When you have all three pieces in a similar position, move your king instead of a check. This forces the opposing king to remain boxed in.</p>
<ol start="6">
<li><p>Kd6 Kf7</p>
</li>
<li><p>Rf5+ Kg6</p>
</li>
<li><p>Ke6</p>
</li>
</ol>
<p>Providing support to the rook and ensuring that the black king remains in a smaller space. This is what the box looks like now:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280233810/fc4df6f2-0355-42ce-82c4-daba5c30fbfd.png" alt="rook and king vs king" class="image--center mx-auto" width="758" height="757" loading="lazy"></p>
<ol start="8">
<li><p>... Kg7</p>
</li>
<li><p>Rg5+ Kh6</p>
</li>
<li><p>Kf6 Kh7</p>
</li>
<li><p>Rh5+ Kg8</p>
</li>
<li><p>Rh6 Kf8</p>
</li>
<li><p>Rh8#</p>
</li>
</ol>
<p>Here are things to keep in mind when playing with a king and rook against a king:</p>
<ul>
<li><p>Cut off the enemy king with your rook.</p>
</li>
<li><p>Bring your king closer to support the rook and push the enemy king.</p>
</li>
<li><p>Shrink the box using the two points above.</p>
</li>
<li><p>Force the king to the edge of the board (first rank, eight rank, a-file, h-file). Checkmate is only possible when the enemy king is at the edge of the board and in opposition with your king.</p>
</li>
</ul>
<p>This can be overwhelming for beginners, so don't worry if you don't fully understand the process from start to finish. With constant practice, it should become easier and faster for you to recognize the patterns. I'll also provide some puzzles to help you practice.</p>
<p>Here's a replay of all the move and the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280265687/7a572c0c-d47f-422f-ae44-b01e82f42892.gif" alt="rook and king vs king replay" class="image--center mx-auto" width="762" height="758" loading="lazy"></p>
<ol>
<li><p>Rb5+ Kd6</p>
</li>
<li><p>Kd4 Ke6</p>
</li>
<li><p>Rd5 Kf6</p>
</li>
<li><p>Re5 Kf7</p>
</li>
<li><p>Kd5 Kf6</p>
</li>
<li><p>Kd6 Kf7</p>
</li>
<li><p>Rf5+ Kg6</p>
</li>
<li><p>Ke6 Kg7</p>
</li>
<li><p>Rg5+ Kh6</p>
</li>
<li><p>Kf6 Kh7</p>
</li>
<li><p>Rh5+ Kg8</p>
</li>
<li><p>Rh6 Kf8</p>
</li>
<li><p>Rh8#</p>
</li>
</ol>
<h4 id="heading-practice-position-for-one-rook-and-king-vs-king-endgamecheckmate-pattern">Practice Position for One Rook and King vs King Endgame/Checkmate Pattern</h4>
<p>You can practice what you learned in the last section using this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280281748/0c091532-cb0d-4e62-8189-f51fbfd01d63.png" alt="rook and king vs king" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>I’ve set up the position for you here: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_w_-_-_0_1?color=black</a>. Click on the link, then click on “CONTINUE FROM HERE” to practice the position against an engine.</p>
<h3 id="heading-how-to-play-the-queen-and-king-vs-king-checkmate-pattern">How to Play the Queen and King vs King Checkmate Pattern</h3>
<p>We’ll start with this board:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280311736/272b9d25-3b61-4946-a8ec-5c7fd41e6b03.png" alt="queen and king vs king" class="image--center mx-auto" width="760" height="758" loading="lazy"></p>
<p>There are a couple of ways to play endgame like the one in the image above. A lot of beginners struggle with this checkmate pattern because they often end in a stalemate or just chase the king around the board until they or their opponent runs out of time.</p>
<p>We can approach this endgame using the direct opposition and box method like we did in the previous section, but there's a more efficient and straightforward way of winning this position, with minimal effort from your king.</p>
<p>We'll use the knight move method. This implies that your queen should only move to squares that imitate a knight attack on the enemy king. Using this method, you can push the king towards the edge of the board.</p>
<p>Here are the possible squares where the queen can go to in order to imitate a knight attack:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280323211/2b3f57e3-7383-4557-907c-b2b8daa5f3bb.png" alt="possible knight attack squares for queen" class="image--center mx-auto" width="760" height="761" loading="lazy"></p>
<p>Let's start with the closest square:</p>
<ol>
<li>... Qd6</li>
</ol>
<p>This brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280332247/e23c4fc2-0465-4420-bde5-f7e12164f05a.png" alt="imaginary box for king" class="image--center mx-auto" width="758" height="760" loading="lazy"></p>
<p>We've pushed the king into a box. Now, no matter what the king plays, try to follow up with moves that imitate a knight attack (the L), and do not play a move that allows the king leave the shrinking box.</p>
<ol start="2">
<li>Ke3 Qd5</li>
</ol>
<p>The keeps the king in the box and brings the queen closer.</p>
<ol start="3">
<li><p>Ke2 Qd4</p>
</li>
<li><p>Kf3 Qe5</p>
</li>
</ol>
<p>The box has gotten smaller:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280345278/cc544086-1dd8-46ca-a8c3-7adfa7c820bd.png" alt="imaginary box for king shrinks " class="image--center mx-auto" width="760" height="760" loading="lazy"></p>
<p>No checks. No direct opposition. Just follow the king with the queen, as though you were playing as a knight.</p>
<ol start="5">
<li><p>Kf2 Qe4</p>
</li>
<li><p>Kg3 Qf5</p>
</li>
<li><p>Kg2 Qf4</p>
</li>
<li><p>Kg1 Qf3</p>
</li>
<li><p>Kh2 Qg4</p>
</li>
<li><p>Kh1</p>
</li>
</ol>
<p>You've successfully pushed the king to the edge of the box. At this point, don't be in a hurry to play another knight attack move with the queen – this will lead to a stalemate.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280354553/a96abe4f-cff0-46cd-98d0-844fa33c2a81.png" alt="queen traps kings at the edge of the board" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>The queen's job is almost done. The white king only has two squares to move to: h2 and h1. It time to push the black king forward to support the queen in a checkmate. Since you've trapped the white king, it will continue to move between the two possible squares until the black king arrives.</p>
<ol start="10">
<li><p>... Ke7</p>
</li>
<li><p>Kh2 Kf6</p>
</li>
<li><p>Kh1 Kf5</p>
</li>
<li><p>Kh2 Kf4</p>
</li>
<li><p>Kh1 Kf3</p>
</li>
<li><p>Kh2 Qg2#</p>
</li>
</ol>
<p>Here's a replay and all the notations:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280366630/10e30dad-f43c-41f1-b3a5-7fca60c3cd4e.gif" alt="replay of queen and king vs king" class="image--center mx-auto" width="758" height="758" loading="lazy"></p>
<ol>
<li><p>... Qd6</p>
</li>
<li><p>Ke3 Qd5</p>
</li>
<li><p>Ke2 Qd4</p>
</li>
<li><p>Kf3 Qe5</p>
</li>
<li><p>Kf2 Qe4</p>
</li>
<li><p>Kg3 Qf5</p>
</li>
<li><p>Kg2 Qf4</p>
</li>
<li><p>Kg1 Qf3</p>
</li>
<li><p>Kh2 Qg4</p>
</li>
<li><p>Kh1 Ke7</p>
</li>
<li><p>Kh2 Kf6</p>
</li>
<li><p>Kh1 Kf5</p>
</li>
<li><p>Kh2 Kf4</p>
</li>
<li><p>Kh1 Kf3</p>
</li>
<li><p>Kh2 Qg2#</p>
</li>
</ol>
<h4 id="heading-practice-position-for-queen-and-king-vs-king-endgamecheckmate-pattern">Practice Position for Queen and King vs King Endgame/Checkmate Pattern</h4>
<p>You can practice what you learned in the last section using this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280380835/2a9fee98-d091-4320-9ca5-974ebba98b26.png" alt="practice position for queen and king vs king" class="image--center mx-auto" width="759" height="757" loading="lazy"></p>
<p>I’ve set up the position for you here: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5q2/8/3K4/8/8_w_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a>. Click on the link, then click on “CONTINUE FROM HERE” to practice the position against an engine.</p>
<p>For this position, choose to play as black before starting the game:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755630967674/d50ef787-4523-48f2-93db-2a8f56825d21.png" alt="choose to play as black" class="image--center mx-auto" width="417" height="698" loading="lazy"></p>
<h3 id="heading-checkmate-patterns-ii">Checkmate Patterns II</h3>
<p>In this section, we’ll deal with checkmate patterns that can happen at any point. That is, you don't have to be in an endgame position/situation to play them.</p>
<p>In some cases, these positions can happen by chance, and in other cases, you have to plan and set them up yourself. The main objective here is to get used to recognizing patterns.</p>
<h4 id="heading-opera-mate">Opera Mate</h4>
<p>An Opera Mate usually involves the following:</p>
<ul>
<li><p>A rook or queen delivering a check along a back rank or file.</p>
</li>
<li><p>A bishop covering a diagonal escape square.</p>
</li>
<li><p>A king trapped by its own pieces or the edge of the board.</p>
</li>
</ul>
<p>Here's an example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280405952/58db2a78-9e42-43e0-a678-2265b4150354.png" alt="opera mate " class="image--center mx-auto" width="761" height="754" loading="lazy"></p>
<p>In the position above, black played Bg7, threatening the white rook. But if we look closely at the position, white can deliver a checkmate by moving to c8.</p>
<p>With Rc8#, the king can't capture the rook because the bishop is protecting it, the king can't move to d7 because the bishop is attacking that square, and unfortunately for the king, its own pawn is blocking it from escaping through e7.</p>
<p>Here's another position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280417490/2d752769-1af0-41df-898c-1fcad3863374.png" alt="opera mate" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>Let's assume that it's white's turn to play again. Would it still be checkmate if the rook moves to c8? Yes it would – the position hasn’t really changed: the bishop is still protecting the rook on c8 and attacking the d7 square, and the pawn on e7 is still blocking the king.</p>
<p>Let's look at an example from <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-iii/PDkQDt6u/YWsqVJDL">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280441952/97afbd7b-3618-406e-8dab-d441968bc6bd.png" alt="opera mate " class="image--center mx-auto" width="745" height="740" loading="lazy"></p>
<p>This game still looks alive, as though both players are still setting up their strategies. It's black's turn to play. At this point, we'll assume that black has discovered a possible opera mate.</p>
<p>The black bishop is attacking the d1 and e2 squares, while the queen can check the king on d1, with additional support from the rook on d8. But, a closer look will reveal something: white has a bishop protecting the d1 square.</p>
<p>So, do you go on to attack or play it safe and find a different strategy? Well, let's evaluate the position, keeping the d1 square in mind.</p>
<p>For black:</p>
<ul>
<li><p>Queen can attack d1.</p>
</li>
<li><p>Rook can support and attack d1.</p>
</li>
<li><p>Bishop can support d1.</p>
</li>
</ul>
<p>For white:</p>
<ul>
<li>Bishop is protecting d1.</li>
</ul>
<p>From this evaluation, you can see that black has a very good advantage. In order to win this game, you must sacrifice the queen. Beginners often avoid sacrifices because we learn chess with the idea that the most power pieces must stay on the board. In this case, it’s the only path to victory.</p>
<p>So:</p>
<ol>
<li>... Qd1+</li>
</ol>
<p>That brings us to this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280458519/e67e476d-f79e-48e1-9d2f-edfa332d8db1.png" alt="opera mate" class="image--center mx-auto" width="746" height="742" loading="lazy"></p>
<p>Black has two options here:</p>
<ul>
<li><p>Capture the queen with the bishop.</p>
</li>
<li><p>Resign.</p>
</li>
</ul>
<p>Let's go with capturing the queen.</p>
<ol start="2">
<li>Bxd1</li>
</ol>
<p>And now, we have this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280468340/3eb6774d-eda7-47d1-9745-4dcc53dd4a30.png" alt="opera mate" class="image--center mx-auto" width="746" height="741" loading="lazy"></p>
<p>Remember the rook on d8?</p>
<ol start="2">
<li>... Rxd1#</li>
</ol>
<p>The rook captures the bishop and wins the game. The king can't capture the rook because it has support from the bishop on g4, it can't escape through e2 because the bishop is attacking that square, and the pawn on f2 is blocking the king.</p>
<p>This shows that you don't have to play until the endgame to win in chess. If you get better at recognizing patterns, you'd be shocked at how many chances you've missed to increase your advantage or win a game.</p>
<h4 id="heading-anastasias-mate">Anastasia's Mate</h4>
<p>Anastasia's Mate is a checkmate pattern that involves a knight and a queen (or rook) working together to trap the opposing king. It involves the following:</p>
<ul>
<li><p>The rook or queen delivering a check.</p>
</li>
<li><p>The knight blocking the king's escape squares (usually two escape squares).</p>
</li>
<li><p>The opposing king trapped by its own pieces.</p>
</li>
</ul>
<p>Consider this position:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280489359/cca92e2e-621f-4f2d-9ead-e491f712f7fc.png" alt="Anastasia's Mate" class="image--center mx-auto" width="759" height="760" loading="lazy"></p>
<p>From the look of things, white has a stronger position. That would be totally true if black didn't have a mate in two opportunity. When black plays Ne2+, it sets up the pattern for Anastasia's mate. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280509251/2d9bf314-9ecc-4265-b884-7249d06a277d.png" alt="Anastasia's Mate" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>The king has two possible squares to move to: h1 and h2.</p>
<ol>
<li><p>... Ne2+</p>
</li>
<li><p>Kh2</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280547179/a78a17bb-ef6d-42b8-8980-d51a21f93272.png" alt="Anastasia's Mate" class="image--center mx-auto" width="760" height="759" loading="lazy"></p>
<p>Is the king safe?</p>
<ol start="2">
<li>... Rh5#</li>
</ol>
<p>The game ends:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280560054/72452d14-636c-4c4e-815f-cf7f324b87ce.png" alt="Anastasia's Mate" class="image--center mx-auto" width="762" height="756" loading="lazy"></p>
<p>The e2 knight blocks the king from going to either g1 or g3, while the rook attacks the h-file. It's easy to miss this pattern for beginners, because we're often used to endgame patterns that involve more "offensive" attacks.</p>
<p>Here's another example from <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/XOkS95uk">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280572013/ffa7a5bd-2953-4341-a2a3-e1920a7e9133.png" alt="Anastasia's Mate" class="image--center mx-auto" width="746" height="743" loading="lazy"></p>
<p>It's not very obvious that this position leads to an Anastasia's mate. You have a bishop attacking the queen, and the queen can capture it and gain more material advantage. But what happens when you sacrifice the queen by capturing the h7 square?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280583338/a0b9dac7-2b19-4893-8f44-a66e95c11ca8.png" alt="Anastasia's Mate" class="image--center mx-auto" width="759" height="754" loading="lazy"></p>
<p>You've sacrificed the queen to force the king to the h7 square, setting it up for Rh5#.</p>
<p>So, even though you may recognize what the Anastasia's Mate looks like, you may have to intentionally lose some pieces to achieve it. This is also applicable to other aspects of chess. Sacrificing pieces can be a perfect way to force your opponent into dangerous situations.</p>
<h4 id="heading-back-rank-mate">Back Rank Mate</h4>
<p>This is a checkmate pattern that you'll encounter a lot in your chess journey. It involves trapping the king behind the pieces in front of it. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280622411/5cba4327-6754-4e2c-94ae-760d34f49230.png" alt="Back Rank Mate" class="image--center mx-auto" width="760" height="754" loading="lazy"></p>
<p>From the image above, you can see the white king trapped behind the three pawns in front of it. To avoid this, you should always remember to create space for your king at some point after castling.</p>
<p>Here's an example from <a target="_blank" href="https://lichess.org/analysis/standard/2r1r1k1/5ppp/8/8/Q7/8/5PPP/4R1K1_w_-_-_0_1?color=white">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280631436/b1a0ddcc-9573-4415-8084-12462ec5abf0.png" alt="Back Rank Mate" class="image--center mx-auto" width="759" height="757" loading="lazy"></p>
<p>It's white's turn to play, and the black king still has three pieces blocking it. The white queen and the rook are both attacking the e8 square, so you can force an exchange that ends the game:</p>
<ol>
<li><p>Rxe8+ Rxe8</p>
</li>
<li><p>Qxe8#</p>
</li>
</ol>
<p>After the trade, you'll have the queen on e8, forcing a checkmate because the king has nowhere to escape to.</p>
<h4 id="heading-smothered-mate">Smothered Mate</h4>
<p>The smothered mate is a checkmate pattern where a knight delivers mate to the enemy king, which is completely trapped/surrounded (or “smothered”) by its own pieces.</p>
<p>Here's what it looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280647104/cb3696e2-aa0f-4114-a8c4-c6d91acded39.png" alt="Smothered Mate" class="image--center mx-auto" width="757" height="759" loading="lazy"></p>
<p>This is a checkmate pattern that shows how powerful the knight can be in endgames. With any other piece, it would be difficult for black to make any significant moves in this situation. But since the knight can jump over pieces when moving and attacking, it can be used in unpredictable ways.</p>
<p>Let's look at an example from <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/UtwzJ9i4">Lichess</a>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280658126/4b53556a-7a96-4e45-9e0b-11ed0c777667.png" alt="Smothered Mate" class="image--center mx-auto" width="759" height="756" loading="lazy"></p>
<p>Again, we'll be sacrificing a piece to gain an advantage. You can sacrifice the white queen with:</p>
<ol>
<li>Qxh7+</li>
</ol>
<p>This forces the black queen to capture:</p>
<ol>
<li>... Qxh7</li>
</ol>
<p>The problem with this is that the king is now trapped:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280674697/43bcbd82-1e7b-4b07-b147-63b213ea23cc.png" alt="Smothered Mate" class="image--center mx-auto" width="759" height="755" loading="lazy"></p>
<p>As beginners, it's often easier to capture a powerful piece than to analyze a position for potential mate patterns. It wouldn’t be surprising to see someone new to chess capturing the queen with the knight.</p>
<p>The best move here is Nf7#:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755280684007/f57d19c2-9072-4cde-b732-93dc5c73a861.png" alt="Smothered Mate" class="image--center mx-auto" width="759" height="758" loading="lazy"></p>
<p>The king is under check and can't escape because it has been trapped by its own pieces.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The handbook showed you some of the common checkmate patterns in chess. But these are not all of them, and not all checkmate patterns are easy to understand for beginners.</p>
<p>While you improve other aspects of your game like strategy and tactics, opening principles, solving puzzles, and so on, it becomes easier to understand certain concepts that seemed too hard at first.</p>
<p>One way to test your understanding of different concepts is by playing against other people or engines. A good place to do this is on Lichess. It’s free, has an active community, and a ton of tools to help you improve your game.</p>
<p>I hope this handbook has been helpful for you on your chess journey. You can <a target="_blank" href="https://lichess.org/@/IHECHIKARA">find me on Lichess @ IHECHIKARA</a>.</p>
<p>You can <a target="_blank" href="https://youtu.be/1AX7_aPWmbE?si=67txQ7Bc-IHZ0lhW">watch the video version of this handbook here</a>.</p>
<h2 id="heading-exercise-answers">Exercise Answers</h2>
<p>Here are the answers to the exercises and practice positions:</p>
<h4 id="heading-files-a-to-f-exercise">Files a to f Exercise</h4>
<p>The arrow is on the c-file. You can tell by looking at the alphabet that corresponds with the vertical line.</p>
<h4 id="heading-ranks-1-to-8-exercise">Ranks 1 to 8 Exercise</h4>
<p>The arrow is on the eight rank. You can tell by looking at the number that corresponds with the horizontal line.</p>
<h4 id="heading-how-to-denote-piece-promotion-in-algebraic-chess-notation">How to Denote Piece Promotion in Algebraic Chess Notation</h4>
<ul>
<li><p>The notation for a pawn that moves to d1 and gets promoted to a rook is d1=R.</p>
</li>
<li><p>The notation for a pawn that moves to b8 and gets promoted to a bishop d1=B.</p>
</li>
<li><p>Here is the final board position for the given notations:</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755632639415/467a3c95-c234-4022-81fd-13867fa6b5ca.png" alt="final position for the given notations in the algebraic chess notations section" class="image--center mx-auto" width="790" height="793" loading="lazy"></p>
<h2 id="heading-practice-position-urls">Practice Position URLs</h2>
<p>Here are the links for all the practice positions:</p>
<ul>
<li><p>Two Rooks vs King Endgame/Checkmate Pattern URL: <a target="_blank" href="https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a>.</p>
</li>
<li><p>One Rook and King vs King Endgame/Checkmate Pattern URL: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black">https://lichess.org/editor/6k1/8/8/5r2/8/3K4/8/8_w_-_-_0_1?color=black</a>.</p>
</li>
<li><p>Queen and King vs King Endgame/Checkmate Pattern URL: <a target="_blank" href="https://lichess.org/editor/6k1/8/8/5q2/8/3K4/8/8_w_-_-_0_1?color=black">https://lichess.org/editor/1r4k1/8/8/5r2/8/3K4/8/8_b_-_-_0_1?color=black</a> (choose to play as black).</p>
</li>
<li><p>Practice many checkmate patterns here: <a target="_blank" href="https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/9rd7XwOw">https://lichess.org/practice/checkmates/checkmate-patterns-i/fE4k21MW/9rd7XwOw</a>. Click on “Practice list” to access more patterns.</p>
</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 Change Background Color with JavaScript – BG Color in JS and HTML ]]>
                </title>
                <description>
                    <![CDATA[ You can style elements with JavaScript using the element's style property. In this article, you'll learn how to change background color using JavaScript. Here's what the mini project you'll build looks like: In the image above, each button changes t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-change-background-color-with-javascript/</link>
                <guid isPermaLink="false">667ee30607498d8fd2726201</guid>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 28 Jun 2024 16:21:26 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_t-l5FFH8VA/upload/7dac186ffa0ba7f32d72ccf06d1d5baf.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can style elements with JavaScript using the element's <code>style</code> property. In this article, you'll learn how to change background color using JavaScript.</p>
<p>Here's what the mini project you'll build looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1719585559018/23123259-9540-40c6-8f1f-3f444c154b2c.png" alt="image showing five buttons that each change the background color of a page" class="image--center mx-auto" width="940" height="434" loading="lazy"></p>
<p>In the image above, each button changes the background color of the page to a specific color.</p>
<p>You can get the starter files for the project <a target="_blank" href="https://github.com/ihechikara/change-bg-color-with-js/tree/main">here</a>.</p>
<p>There are five buttons in the <strong>index.html</strong> file, and each of them changes the background color to a specific value:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Change BG Color With JS<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Choose background color<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Blue<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Green<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Yellow<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Reset<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
​
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
​
</code></pre>
<p>You won't be making any changes to the <strong>style.css</strong> file. Its purpose is to center the elements on the page and style the buttons to have the same size.</p>
<p>At the moment, nothing happens when you click on the buttons. Let's write the logic for that in the <strong>script.js</strong> file.</p>
<h2 id="heading-how-to-change-background-color-with-javascript">How to Change Background Color with JavaScript</h2>
<p>To change the background color of an element with JavaScript, you can use the element's <code>style</code> property:</p>
<p>Here's how:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setBgGreen</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">'green'</span>;
}
​
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setBgRed</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">'red'</span>;
}
​
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setBgBlue</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">'blue'</span>;
}
​
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setBgYellow</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">'yellow'</span>;
}
​
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">defaultBgColor</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">'white'</span>;
}
</code></pre>
<p>In the code above, we created five functions: <code>setBgGreen()</code>, <code>setBgRed()</code>, <code>setBgBlue()</code>, <code>setBgYellow()</code>, and <code>defaultBgColor()</code>.</p>
<p>Each function has one thing in common: they all target the <code>body</code>. Through the <code>body</code> element (which represents the webpage), we accessed the <code>style.backgroundColor</code> property. The property returns or sets the background color of an element.</p>
<p>So:</p>
<ul>
<li><p><code>document.body.style.backgroundColor = 'green';</code> in the <code>setBgGreen()</code> function sets the background color of <code>body</code> to green.</p>
</li>
<li><p><code>document.body.style.backgroundColor = 'red';</code> in the <code>setBgRed()</code> function sets the background color of <code>body</code> to red.</p>
</li>
<li><p><code>document.body.style.backgroundColor = 'blue';</code> in the <code>setBgBlue()</code> function sets the background color of <code>body</code> to blue.</p>
</li>
<li><p><code>document.body.style.backgroundColor = 'yellow';</code> in the <code>setBgYellow()</code> function sets the background color of <code>body</code> to yellow.</p>
</li>
<li><p><code>document.body.style.backgroundColor = 'white';</code> in the <code>defaultBgColor()</code> function sets the background color of <code>body</code> to white.</p>
</li>
</ul>
<p>Next, you'll assign each function to their respective button using the <code>onclick</code> attribute in your HTML file. This is what your <strong>index.html</strong> file should look like after that:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Change BG Color With JS<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Choose background color<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"setBgRed()"</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"setBgBlue()"</span>&gt;</span>Blue<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"setBgGreen()"</span>&gt;</span>Green<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"setBgYellow()"</span>&gt;</span>Yellow<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"defaultBgColor()"</span>&gt;</span>Reset<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
​
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>When you click the buttons, you should see the background color of the page change to the color assigned to the button.</p>
<p>Note that this is not only applicable to the <code>body</code> element. You can do this for specific parts of your page as well.</p>
<p>For a example, the background color of a <code>div</code> with an <code>id</code> of <code>container</code> can be changed using <code>container.style.backgroundColor = "red"</code> .</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to change background color with JavaScript using an element's <code>style</code> property.</p>
<p>You can find the full project code <a target="_blank" href="https://github.com/ihechikara/change-bg-color-with-js/tree/feat/change-bg-color">here</a>.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Git Checkout Remote Branch – How to Fetch and List Remote Branches ]]>
                </title>
                <description>
                    <![CDATA[ You can use branches in Git to work on different features without affecting your main codebase. For example, you can experiment with a new layout for your webpage on a different branch without affecting the main branch where your website is being dep... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/git-checkout-remote-branch-how-to-fetch-and-list-remote-branches/</link>
                <guid isPermaLink="false">66312218ca07c0eea04f8067</guid>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ version control ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 30 Apr 2024 16:53:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UT8LMo-wlyk/upload/c907bdb799b1331e27dd68f35a2b2e25.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use branches in Git to work on different features without affecting your main codebase. For example, you can experiment with a new layout for your webpage on a different branch without affecting the main branch where your website is being deployed from.</p>
<p>Branches are used for different purposes like feature development, bug fixes, versioning, experimentation, <a target="_blank" href="https://contribute.freecodecamp.org/#/">contributing to open source projects</a>, and so on.</p>
<p>In this article, you'll learn how to use different Git commands to interact with remote branches.</p>
<h1 id="heading-how-to-fetch-and-list-remote-branches">How to Fetch and List Remote Branches</h1>
<p>I've created a repository (repo) for this article with three different branches: main, feat/create-hobbies-list, and feat/create-language-list. You can download the repo <a target="_blank" href="https://github.com/ihechikara/git-branches-article">here</a>, or clone it to your computer using this command:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/ihechikara/git-branches-article.git
</code></pre>
<p>The command above downloads the main branch of the repository to your computer.</p>
<p>Feel free to follow along with your own codebase/Git repo.</p>
<h2 id="heading-how-to-list-remote-branches">How to List Remote Branches</h2>
<p>When you look at the repo you just cloned on GitHub, you'll notice that there are three branches.</p>
<p>But when you run the <code>git branch</code> command, you'll only get a list of branches in the local repo. In our case, that is the main branch. This happens for a couple of reasons:</p>
<ul>
<li><p>The <code>git branch</code> command only shows local branches.</p>
</li>
<li><p>Cloning a branch doesn't automatically download all other branches in the remote repo.</p>
</li>
</ul>
<p>So how do you list the remote branches? You can do that using the <code>git branch -r</code> command:</p>
<pre><code class="lang-bash">git branch -r

origin/HEAD -&gt; origin/main
origin/feat/create-hobbies-list
origin/feat/create-language-list
origin/main
</code></pre>
<p>From the command output above, you can see all the branches in the remote repo. The main branch which also acts as the default branch (origin/HEAD), and two other branches: feat/create-hobbies-list and feat/create-language-list.</p>
<p>Now that you know how to list remote branches, let's see how to fetch and work on them locally.</p>
<h2 id="heading-how-to-fetch-remote-branches">How to Fetch Remote Branches</h2>
<p>You can fetch remote branches for different reasons like code review, updating your local repo with changes made to the remote repo, experimentation, and so on.</p>
<h3 id="heading-how-to-fetch-remote-branches-using-git-fetch">How to Fetch Remote Branches Using <code>git fetch</code></h3>
<p>You can use the <code>git fetch</code> command to "fetch" recent changes made to the remote repo without merging them into your local repo.</p>
<p>For example, let's assume that new changes were pushed to the feat/create-language-list branch. When you run the <code>git fetch</code> command, Git retrieves the new changes in the remote repo but you won't see them in my local branch/repo.</p>
<p>You can then use commands like <code>git diff</code> and <code>git log</code> to compare the changes.</p>
<p>In a case where you're satisfied with the changes, you can use the <code>git merge</code> command to merge those changes into your local branch. At this point, the changes from the remote branch will be visible/seen locally.</p>
<p>That is:</p>
<pre><code class="lang-bash">git checkout feat/create-language-list
</code></pre>
<p>The command above switches to the feat/create-language-list branch.</p>
<pre><code class="lang-bash">git fetch
</code></pre>
<p>The command above retrieves current changes made to the remote branch that aren't in your local branch.</p>
<pre><code class="lang-bash">git diff feat/create-language-list origin/feat/create-language-list
</code></pre>
<p>The command above compares the changes you just fetched with your local branch. In the terminal, the red characters denote the state of your local branch while the green characters denote new changes from the remote branch. That is:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714451407216/fd2ec3a7-a20f-4c1f-94a1-d7e916f183d4.png" alt="git diff command showing changes retrieved from remote branch" class="image--center mx-auto" width="502" height="466" loading="lazy"></p>
<pre><code class="lang-bash">git merge
</code></pre>
<p>The command above merges the changes into your local branch. In this case, the <strong>languages.txt</strong> file will be updated with the new changes.</p>
<p>In summary, <code>git fetch</code> retrieves the changes while <code>git merge</code> merges the changes to your local branch.</p>
<h3 id="heading-how-to-fetch-remote-branches-using-git-pull">How to Fetch Remote Branches Using <code>git pull</code></h3>
<p>The <code>git pull</code> command is similar to <code>git fetch</code> and <code>git merge</code>.</p>
<p>The difference is that <code>git pull</code> automatically merges new changes into your local branch. That is, you don't get to compare changes before merging (you won't get the chance to run <code>git diff</code>).</p>
<p><code>git pull</code> executes both <code>git fetch</code> and <code>git merge</code> at the same time.</p>
<p>So once you run the <code>git pull</code> command, the remote changes will appear locally if there are no merge conflicts.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this article, you learned how to list remote branches using the <code>git branch -r</code> command.</p>
<p>You also learned how to fetch remote branches. The <code>git fetch</code> command fetches changes from the remote branch while the <code>git merge</code> command merges the remote changes to your local branch. This process give you the opportunity to compare changes before merging them.</p>
<p>On the other hand, the <code>git pull</code> command automatically fetches and merges changes from a remote branch as long as there are no merge conflicts.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Bytes to String – How to Convert a Str to Bytes and Back Again ]]>
                </title>
                <description>
                    <![CDATA[ You can use bytes in Python to represent data in binary form. In this article, you'll learn how to convert bytes to a string, and vice versa. Before we look at the conversions, let's talk about how bytes work in Python. You can skip to the next secti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-bytes-to-string-code-examples/</link>
                <guid isPermaLink="false">661eda8b3eead5a3179facaf</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 16 Apr 2024 20:07:39 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zGuBURGGmdY/upload/6d5b13a8926b01576cba45ee0d72bfc8.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use bytes in Python to represent data in binary form. In this article, you'll learn how to convert bytes to a string, and vice versa.</p>
<p>Before we look at the conversions, let's talk about how bytes work in Python. You can skip to the next section if you already understand this, or you're just interested in the conversions.</p>
<h2 id="heading-how-bytes-work-in-python">How Bytes Work in Python</h2>
<p>You can create byte literals by prefixing the <code>b</code> notation. This tells the Python interpreter that a set of characters should be treated as bytes. Here's an example:</p>
<pre><code class="lang-python">byte_data = <span class="hljs-string">b'Hello'</span>
</code></pre>
<p>In the code above, we prefixed <code>b</code> right before the string value: <code>b'Hello'</code>. If you print the characters in the string, you'll get a binary value for each. That is:</p>
<pre><code class="lang-python">byte_data = <span class="hljs-string">b'Hello'</span>
print(byte_data[<span class="hljs-number">0</span>]) <span class="hljs-comment"># 72</span>
</code></pre>
<p>So instead of "H", 72 was returned. If you go on to print the value of each index in the sequence, you should get their binary values:</p>
<pre><code class="lang-python">byte_data = <span class="hljs-string">b'Hello'</span>
print(byte_data[<span class="hljs-number">0</span>]) <span class="hljs-comment"># 72 =&gt; H</span>
print(byte_data[<span class="hljs-number">1</span>]) <span class="hljs-comment"># 101 =&gt; e</span>
print(byte_data[<span class="hljs-number">2</span>]) <span class="hljs-comment"># 108 =&gt; l</span>
print(byte_data[<span class="hljs-number">3</span>]) <span class="hljs-comment"># 108 =&gt; l</span>
print(byte_data[<span class="hljs-number">4</span>]) <span class="hljs-comment"># 111 =&gt; 0</span>
</code></pre>
<p>Now let's talk about how to convert a string to bytes, and how to convert bytes to a string.</p>
<h1 id="heading-how-to-convert-a-str-to-bytes-in-python">How to Convert a Str to Bytes in Python</h1>
<p>You can use the <code>encode()</code> method to convert a string to bytes in Python. The method simply encodes a string using a specific encoding like UTF-8, ASCII, and so on.</p>
<p>Here's an example:</p>
<pre><code class="lang-python">string_data = <span class="hljs-string">"Hello"</span>
print(string_data[<span class="hljs-number">0</span>]) <span class="hljs-comment"># H</span>
</code></pre>
<p>In the code above, we created a string called <code>string_data</code> with a value of "Hello". We also printed the first character of the string, which is "H".</p>
<p>Now let's convert the string to bytes using the <code>encode()</code> method:</p>
<pre><code class="lang-python">string_data = <span class="hljs-string">"Hello"</span>
byte_data = string_data.encode(<span class="hljs-string">'utf-8'</span>)
print(byte_data[<span class="hljs-number">0</span>]) <span class="hljs-comment"># 72</span>
</code></pre>
<p>We converted the <code>string_data</code> variable to bytes using the <code>encode()</code> method which took "utf-8" as a parameter. We stored this conversion in the <code>byte_data</code> variable: <code>byte_data = string_data.encode('utf-8')</code>.</p>
<p>Lastly, we printed the first character of the <code>byte_data</code> variable and got a binary value: <code>print(byte_data[0]) # 72</code>.</p>
<h1 id="heading-how-to-convert-bytes-to-a-str-to-in-python">How to Convert Bytes to a Str to in Python</h1>
<p>You can use the <code>decode()</code> method to convert bytes to a string in Python. It works just like the <code>encode()</code> variable: attach the variable to be converted using dot notation and specify the encoding type as the method's parameter.</p>
<p>Here's an example:</p>
<pre><code class="lang-python">byte_data = <span class="hljs-string">b'Hello'</span>
string_data = byte_data.decode(<span class="hljs-string">'utf-8'</span>)
print(string_data[<span class="hljs-number">0</span>]) <span class="hljs-comment"># H</span>
</code></pre>
<p>In the code above, we created a bytes object called <code>byte_data</code>.</p>
<p>Using the <code>decode()</code> method, we converted it to a string and stored it in a <code>string_data</code> variable: <code>string_data = byte_data.decode('utf-8')</code>.</p>
<p>When you print the characters of the <code>string_data</code> variable, you should get string characters instead of binary values: <code>print(string_data[0]) # H</code></p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this article, you learned how to use bytes in Python. You also learned two conversion methods:</p>
<ul>
<li><p>How to convert a string to bytes using the <code>encode()</code> method.</p>
</li>
<li><p>How to convert bytes to a string using the <code>decode()</code> method.</p>
</li>
</ul>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Break Statement – How to Break Out of a For Loop in Python ]]>
                </title>
                <description>
                    <![CDATA[ You can use loops in Python to execute code logic repeatedly until a specified condition is met. Python provides some built-in control statements that let you change the behavior of a loop. Some of these control statements include continue, break, pa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-break-statement-tutorial/</link>
                <guid isPermaLink="false">6616c3899fd7ac3907ca544c</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 10 Apr 2024 16:51:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ieic5Tq8YMk/upload/1e00a0a8acc5c22dea9a4910bffecbb1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use loops in Python to execute code logic repeatedly until a specified condition is met.</p>
<p>Python provides some built-in control statements that let you change the behavior of a loop. Some of these control statements include <code>continue</code>, <code>break</code>, <code>pass</code>, and <code>else</code>.</p>
<p>In this article, you'll learn how to terminate the current loop or a switch statement using the <code>break</code> statement.</p>
<h2 id="heading-how-to-use-the-break-statement-in-a-python-for-loop">How to Use the <code>break</code> Statement in a Python <code>for</code> Loop</h2>
<p>Consider the Python list below:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]
</code></pre>
<p>You can use a <code>for</code> loop to iterate through and print the elements of the <code>usernames</code> list:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> usernames:
    print(i)
<span class="hljs-comment"># Jade</span>
<span class="hljs-comment"># John</span>
<span class="hljs-comment"># Jane</span>
<span class="hljs-comment"># Doe</span>
</code></pre>
<p>But what if you want to stop the loop when a particular username is found? You can do this using the <code>break</code> statement.</p>
<p>Here's an example:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> usernames:
    print(i)
    <span class="hljs-keyword">if</span> i == <span class="hljs-string">"John"</span>:
        <span class="hljs-keyword">break</span>
<span class="hljs-comment"># Jade</span>
<span class="hljs-comment"># John</span>
</code></pre>
<p>In the code above, we created an <code>if</code> statement that checks whether the current value of <code>i</code> is "John": <code>if i == "John"</code>.</p>
<p>In the body of the <code>if</code> statement, we used the <code>break</code> statement. So the loop will stop when it finds an element in the list with the value of "John".</p>
<p>So instead of printing the whole list ("Jade", "John", "Jane", "Doe"), "Jade" and "John" were printed because the loop stopped immediately after it found "John".</p>
<h2 id="heading-how-to-use-the-break-statement-in-a-python-while-loop">How to Use the <code>break</code> Statement in a Python <code>while</code> Loop</h2>
<p>You can terminate a <code>while</code> loop using the <code>break</code> statement:</p>
<pre><code class="lang-python">usernames = [<span class="hljs-string">"Jade"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Doe"</span>]

i = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> i &lt; len(usernames):
    print(usernames[i])
    <span class="hljs-keyword">if</span> usernames[i] == <span class="hljs-string">"John"</span>:
        <span class="hljs-keyword">break</span>
    i += <span class="hljs-number">1</span>
</code></pre>
<p>Just like we did in the <code>for</code> loop example, we created a <code>usernames</code> list with four elements: <code>["Jade", "John", "Jane", "Doe"]</code>.</p>
<p>Using an <code>if</code> statement in the <code>while</code> loop, we checked when the current loop was at the index with a value "John". When that happens, the loop is terminated.</p>
<p>Once again, "Jade" and "John" were printed because the loop stops when "John" is found.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned to use the <code>break</code> statement in Python. You can use it to terminate the current loop when a condition is met.</p>
<p>From the above examples, you learned how to use the <code>break</code> statement to terminate <code>for</code> and <code>while</code> loops in Python.</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[ How to Add Google Analytics to your Astro Website ]]>
                </title>
                <description>
                    <![CDATA[ You can use data insights derived from your website or app to make important decisions that'll help grow your business. This information can help you improve user experience, create effective content strategies, and so on. Google Analytics is an effe... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-add-google-analytics-to-your-astro-website/</link>
                <guid isPermaLink="false">66b0a2bfb30dd4d00547bb92</guid>
                
                    <category>
                        <![CDATA[ analytics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Astro ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Google Analytics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Wed, 18 Oct 2023 18:07:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/andy-hermawan-bVBvv5xlX3g-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use data insights derived from your website or app to make important decisions that'll help grow your business. This information can help you improve user experience, create effective content strategies, and so on.</p>
<p>Google Analytics is an effective tool for tracking and analyzing traffic and events on your websites and mobile apps. In this article, you'll learn how to add Google Analytics to your Astro website.</p>
<p>To follow along, you'll need the following:</p>
<ul>
<li>A Google account.</li>
<li>A deployed Astro project.</li>
</ul>
<p>Let's get started!</p>
<h2 id="heading-how-to-add-google-analytics-to-an-astro-website">How to Add Google Analytics to an Astro Website</h2>
<p>Before adding Google analytics, make sure you've already deployed your project. Here's one that I've deployed using Netlify: <a target="_blank" href="https://astro-article.netlify.app/">https://astro-article.netlify.app/</a>. This is an Astro blog template created with the <code>npm create astro@latest -- --template blog</code> command.</p>
<p>This section will be divided into two sub-sections. In the first sub-section, you'll learn how to create an Analytics account and how to set up your account for tracking and monitoring your website.</p>
<p>In the second sub-section, you'll learn how to configure your code to sync with Google Analytics.</p>
<h3 id="heading-how-to-set-up-google-analytics">How to Set Up Google Analytics</h3>
<p>You can follow these steps to set up Google Analytics:</p>
<h4 id="heading-step-1-account-creation-page">Step #1 – Account Creation Page</h4>
<p>The first step is to create a Google Analytics account. You can do that by visiting <a target="_blank" href="https://analytics.google.com/">the Google Analytics website</a>.</p>
<p>When the page loads, you should see something similar to this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/google-analytics-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Google Analytics home page</em></p>
<p>Click on the "Start measuring" button. This will take you to the account creation page where you'll fill in some info about your website/app. That is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/account-creation.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Create an Account" page on Google Analytics</em></p>
<p>After inputting an account name, scroll down the page and click on the "Next" button.</p>
<h4 id="heading-step-2-property-creation-page">Step #2 – Property Creation Page</h4>
<p>On the property creation page, you can create a property name, time zone, and currency.</p>
<p>A property acts as a unique identifier for your websites and apps. So it is like a container for all the data related to a specified website or app.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/property-creation.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Create a Property" page on Google Analytics</em></p>
<h4 id="heading-step-3-business-details-page">Step #3 – Business Details Page</h4>
<p>On the business details page, you can specify your industry category and the business size.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/business-details.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Describe your business" page on Google Analytics</em></p>
<h4 id="heading-step-4-business-objectives-page">Step #4 – Business Objectives Page</h4>
<p>The business objectives helps Analytics generate personalized reports for your business. You can select the options that are important to your website, app, or product category.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/business-objectives.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Business objectives" page on Google Analytics</em></p>
<p>After selecting the options, click on the "Create" button.</p>
<h4 id="heading-step-5-data-collection-page">Step #5 – Data Collection Page</h4>
<p>On the data collection page, you can choose between different platforms to collect data from. Since we're working with a website, we'll go with the Web option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/data-collection.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Start collecting data" page on Google Analytics</em></p>
<p>Next, you'll have to create a data stream by inputting your website URL and your stream name (this can be whatever you want, but I'll recommend using a name related to your website).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/stream.png" alt="Image" width="600" height="400" loading="lazy">
<em>Page to setup a data stream on Google Analytics</em></p>
<p>In my data stream information, I used <a target="_blank" href="https://astro-article.netlify.app/">https://astro-article.netlify.app/</a> as the URL and "Astro Blog Template" as the stream name. </p>
<p>Make sure you remove the "https://" part of the link in the input box so you don't get the "Valid website URL is required" error. </p>
<p>So instead of <a target="_blank" href="https://astro-article.netlify.app/">https://astro-article.netlify.app/</a>, it should be astro-article.netlify.app/.</p>
<p>This is what mine looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/stream-data.png" alt="Image" width="600" height="400" loading="lazy">
<em>Example of information entered properly in data stream setup page</em></p>
<p>Go ahead and click on the "Create stream" button.</p>
<p>On the next page/prompt, you'll see your stream name, URL, ID, and measurement ID values. </p>
<p>The measurement ID will be important in our code integration so you can copy and paste it somewhere.</p>
<p>Here's what the page looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/stream-details.png" alt="Image" width="600" height="400" loading="lazy">
<em>"Web stream details" page on Google Analytics</em></p>
<p>If you click on "View tag instructions", you'll see a code snippet for manual integration with code. Copy the code and paste somewhere because we'll make use of it soon.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/installation-instructions.png" alt="Image" width="600" height="400" loading="lazy">
<em>Installation instructions</em></p>
<p>Here's the code snippet if you missed it:</p>
<pre><code class="lang-js">&lt;!-- Google tag (gtag.js) --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">async</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">window</span>.dataLayer = <span class="hljs-built_in">window</span>.dataLayer || [];
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">gtag</span>(<span class="hljs-params"></span>)</span>{dataLayer.push(<span class="hljs-built_in">arguments</span>);}
  gtag(<span class="hljs-string">'js'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());

  gtag(<span class="hljs-string">'config'</span>, <span class="hljs-string">'MEASUREMENT_ID'</span>);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>If you're copying the code above, make sure you replace the two <code>MEASUREMENT_ID</code> values with the actual value of your measurement ID.</p>
<h3 id="heading-how-to-integrate-google-analytics-and-astro">How to Integrate Google Analytics and Astro</h3>
<p>At this point, we've created a Google Analytics account and generated our project's measurement ID. The next thing to do is to sync our code to Google Analytics.</p>
<p>But first, we have to install a library called Partytown. When using third party integrations, you may run into performance issues because you're making use of third-party code.</p>
<p>Partytown allows these integrations to run as expected without reducing your site's performance. You can read more about that <a target="_blank" href="https://partytown.builder.io/how-does-partytown-work">here</a>.</p>
<h4 id="heading-step-1-install-partytown">Step #1 – Install Partytown</h4>
<p>Head to your Astro project terminal and run this command to install Partytown:</p>
<pre><code class="lang-bash">npm install @astrojs/partytown
</code></pre>
<h4 id="heading-step-2-configure-partytown">Step #2 – Configure Partytown</h4>
<p>After the installation is complete, you'll need to add the integration to your <strong>astro.config.mjs</strong> file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'astro/config'</span>;
<span class="hljs-keyword">import</span> mdx <span class="hljs-keyword">from</span> <span class="hljs-string">'@astrojs/mdx'</span>;
<span class="hljs-keyword">import</span> partytown <span class="hljs-keyword">from</span> <span class="hljs-string">'@astrojs/partytown'</span>

<span class="hljs-keyword">import</span> sitemap <span class="hljs-keyword">from</span> <span class="hljs-string">'@astrojs/sitemap'</span>;

<span class="hljs-comment">// https://astro.build/config</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    <span class="hljs-attr">site</span>: <span class="hljs-string">'https://astro-article.netlify.app/'</span>,
    <span class="hljs-attr">integrations</span>: [
        mdx(), 
        sitemap(),
        partytown({
            <span class="hljs-attr">config</span>: {
              <span class="hljs-attr">forward</span>: [<span class="hljs-string">"dataLayer.push"</span>],
            },
        }),
    ],
});
</code></pre>
<p>In the code above, we imported the Partytown library: <code>import partytown from '@astrojs/partytown'</code>.</p>
<p>We then added this piece of code to the <code>integrations</code> object:</p>
<pre><code class="lang-js">partytown({
      <span class="hljs-attr">config</span>: {
        <span class="hljs-attr">forward</span>: [<span class="hljs-string">"dataLayer.push"</span>],
      },
})
</code></pre>
<p>Everything else in the code came with the Astro project.</p>
<h4 id="heading-step-3-add-google-tag-to-your-pages">Step #3 – Add Google Tag to your Pages</h4>
<p>Remember the code snippet from Google Analytics? This is where we'll use it.</p>
<pre><code class="lang-js">&lt;!-- Google tag (gtag.js) --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/partytown"</span> <span class="hljs-attr">async</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/partytown"</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">window</span>.dataLayer = <span class="hljs-built_in">window</span>.dataLayer || [];
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">gtag</span>(<span class="hljs-params"></span>)</span>{dataLayer.push(<span class="hljs-built_in">arguments</span>);}
  gtag(<span class="hljs-string">'js'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());

  gtag(<span class="hljs-string">'config'</span>, <span class="hljs-string">'MEASUREMENT_ID'</span>);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>Note that we added the <code>type="text/partytown"</code> attribute to both <code>&lt;script&gt;</code> tags.</p>
<p>Remember to change the <code>MEASUREMENT_ID</code> values to the value of your measurement ID. Mine looks like this:</p>
<pre><code class="lang-js">&lt;!-- Google tag (gtag.js) --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/partytown"</span> <span class="hljs-attr">async</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://www.googletagmanager.com/gtag/js?id=G-KM36S70L8Y"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/partytown"</span>&gt;</span><span class="javascript">
    <span class="hljs-built_in">window</span>.dataLayer = <span class="hljs-built_in">window</span>.dataLayer || [];
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">gtag</span>(<span class="hljs-params"></span>)</span>{dataLayer.push(<span class="hljs-built_in">arguments</span>);}
    gtag(<span class="hljs-string">'js'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());

    gtag(<span class="hljs-string">'config'</span>, <span class="hljs-string">'G-KM36S70L8Y'</span>);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>Do not use the snippet above as it has my measurement ID so it's already associated with my website (not my actual website :)). Copy the first code snippet and change the <code>MEASUREMENT_ID</code> values to the value of your measurement ID.</p>
<p>To track and monitor a page, you need to paste the code snippet in that page. Copy the code and paste it in the <code>&lt;head&gt;</code> section of every page file (<strong>index.astro</strong>, <strong>BlogPost.astro</strong>, and so on) you want to track and analyze using Google Analytics.</p>
<p>Here's an example using the <strong>index.astro</strong> file in the <strong>pages</strong> directory:</p>
<pre><code class="lang-js">---
<span class="hljs-keyword">import</span> BaseHead <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/BaseHead.astro'</span>;
<span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Header.astro'</span>;
<span class="hljs-keyword">import</span> Footer <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/Footer.astro'</span>;
<span class="hljs-keyword">import</span> { SITE_TITLE, SITE_DESCRIPTION } <span class="hljs-keyword">from</span> <span class="hljs-string">'../consts'</span>;
---

&lt;!doctype html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Google tag (gtag.js) --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/partytown"</span> <span class="hljs-attr">async</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/partytown"</span>&gt;</span><span class="javascript">
            <span class="hljs-built_in">window</span>.dataLayer = <span class="hljs-built_in">window</span>.dataLayer || [];
            <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">gtag</span>(<span class="hljs-params"></span>)</span>{dataLayer.push(<span class="hljs-built_in">arguments</span>);}
            gtag(<span class="hljs-string">'js'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());

            gtag(<span class="hljs-string">'config'</span>, <span class="hljs-string">'MEASUREMENT_ID'</span>);
        </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">BaseHead</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{SITE_TITLE}</span> <span class="hljs-attr">description</span>=<span class="hljs-string">{SITE_DESCRIPTION}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
... <span class="hljs-comment">&lt;!-- The rest of the HTML code --&gt;</span></span>
</code></pre>
<p>In the code above, we put the code from Google Analytics in the <code>&lt;head&gt;</code> tag. You can do this for all the pages you want to track and monitor.</p>
<p>Remember to add the  <code>type="text/partytown"</code> attribute to the <code>&lt;script&gt;</code> tags, and to change <code>MEASUREMENT_ID</code> (used in two places in the snippet) to the value of your measurement ID.</p>
<h4 id="heading-step-4-build-and-deploy-your-project">Step #4 – Build and Deploy your Project</h4>
<p>Deploy your project using your preferred process.</p>
<p>In my case, I use <code>npm run build</code> to build into the <strong>dist</strong> folder, and then push the code to GitHub. This automatically triggers a Netlify deployment.</p>
<p>You don't have to use my method, but make sure your project builds before deployment.</p>
<p>Once your website has been deployed, you may have to wait up to 48 hours to start seeing your analytics in the Google Analytics dashboard.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/pending-data-collection.png" alt="Image" width="600" height="400" loading="lazy">
<em>Pending page</em></p>
<p>You'll see this page when you click on the "Continue to Home" button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/analytics-home.png" alt="Image" width="600" height="400" loading="lazy">
<em>Analytics dashboard</em></p>
<p>This is your Analytics dashboard. You can view and analyze your data here when there's data available.</p>
<p>And there you have it! You've successfully integrated your project with Google Analytics.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we saw how to add Google Analytics to an Astro project. This can be used to track and analyze traffic and events on websites and apps.</p>
<p>We saw how to create and set up an Analytics account. </p>
<p>We then saw how to integrate Google Analytics to an Astro project using code.</p>
<p>Happy coding! You can read more Astro tutorials on <a target="_blank" href="https://ihechikara.com/">my blog</a>.</p>
 ]]>
                </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[ Pandas Count Rows – How to Get the Number of Rows in a Dataframe ]]>
                </title>
                <description>
                    <![CDATA[ Pandas is a library built on the Python programming language. You can use it to analyze and manipulate data. A dataframe is two-dimensional data structure in Pandas that organizes data in a tabular format with rows and columns.  In this article, you'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/pandas-count-rows-how-to-get-the-number-of-rows-in-a-dataframe/</link>
                <guid isPermaLink="false">66b0a32e6428eb897141f888</guid>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pandas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 19 May 2023 15:11:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/nacho-capelo-hMXuZrfmCWM-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Pandas is a library built on the Python programming language. You can use it to analyze and manipulate data.</p>
<p>A dataframe is two-dimensional data structure in Pandas that organizes data in a tabular format with rows and columns. </p>
<p>In this article, you'll learn how to get the number of rows in a dataframe using the following: </p>
<ul>
<li>The <code>len()</code> function.</li>
<li>The <code>shape</code> attribute.</li>
<li>The <code>index</code> attribute.</li>
<li>The <code>axes</code> attribuite. </li>
</ul>
<h2 id="heading-how-to-get-the-number-of-rows-in-a-dataframe-using-the-len-function">How to Get the Number of Rows in a Dataframe Using the <code>len()</code> Function</h2>
<p>You can use the <code>len()</code> function to return the length of an object. With a dataframe, the function returns the number of rows. </p>
<p>Consider the dataframe below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>name</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>0</td><td>John</td><td>2</td></tr>
<tr>
<td>1</td><td>Jane</td><td>10</td></tr>
<tr>
<td>2</td><td>Jade</td><td>3</td></tr>
</tbody>
</table>
</div><p>In the example above, we created a dataframe with three rows — row 0, 1, and 2. </p>
<p>You can use the <code>len()</code> function to verify the number of rows: </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df

num_of_rows = len(df)

print(<span class="hljs-string">f"The number of rows is <span class="hljs-subst">{num_of_rows}</span>"</span>)
<span class="hljs-comment"># The number of rows is 3</span>
</code></pre>
<p>In the code above, we passed the dataframe as a parameter to the <code>len()</code> function and stored it in a variable called <code>num_of_rows</code>: </p>
<pre><code class="lang-python">num_of_rows = len(df)
</code></pre>
<p>When <code>num_of_rows</code> was printed, we got a value of 3 (the number of rows).</p>
<h2 id="heading-how-to-get-the-number-of-rows-in-a-dataframe-using-the-shape-attribute">How to Get the Number of Rows in a Dataframe Using the <code>shape</code> Attribute</h2>
<p>The <code>shape</code> attribute returns a tuple with the number of rows and columns in a dataframe.</p>
<p>Here's an example using the same dataframe as in the last section: </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df

num_of_rows = df.shape

print(num_of_rows)
<span class="hljs-comment"># (3, 2)</span>
</code></pre>
<p>In the code above, a tuple — (3, 2) — was returned when we used the <code>shape</code> attribute on the dataframe: <code>df.shape</code>. </p>
<p>The first value, 3, is the number of rows in the dataframe while the second value, 2, is the number of columns. </p>
<p>Since we're only interested in the number of rows, we can extract just that value using its index in the tuple (remember that index numbers start at 0). That is:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df

num_of_rows = df.shape[<span class="hljs-number">0</span>]

print(<span class="hljs-string">f"The number of rows is <span class="hljs-subst">{num_of_rows}</span>"</span>)
<span class="hljs-comment"># The number of rows is 3</span>
</code></pre>
<p>Now we're getting just the number of rows using its index in the tuple: <code>df.shape[0]</code>. </p>
<h2 id="heading-how-to-get-the-number-of-rows-in-a-dataframe-using-the-index-attribute">How to Get the Number of Rows in a Dataframe Using the <code>index</code> Attribute</h2>
<p>You can use the <code>index</code> attribute to access the number of elements in a dataframe, which corresponds with the number of rows. </p>
<p>You can do this in two different ways: </p>
<ul>
<li>Using the <code>index</code> attribute's <code>size</code> property. </li>
<li>Passing the <code>index</code> property as a parameter to the <code>len()</code> function. </li>
</ul>
<p>Here are examples to explain the methods above: </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df

num_of_rows = df.index.size

print(<span class="hljs-string">f"The number of rows is <span class="hljs-subst">{num_of_rows}</span>"</span>)
<span class="hljs-comment"># The number of rows is 3</span>
</code></pre>
<p>In the example above, we accessed the number of rows in the dataframe using <code>df.index.size</code>.</p>
<p>Without the <code>size</code> property, you'd get a result like this: <code>RangeIndex(start=0, stop=3, step=1)</code>. </p>
<ul>
<li><code>start</code> denotes the first index number.</li>
<li><code>stop</code> denotes the number of rows in the dataframe. </li>
<li><code>step</code> denotes the way indexes are incremented (indexes are increased by 1 in our case).</li>
</ul>
<p>So the <code>size</code> property is way of specifying that you're only interested in the number of elements in the dataframe. </p>
<p>Here's another example that uses the <code>len()</code> function: </p>
<pre><code class="lang-pyhon">import pandas as pd

data = {
  "name": ["John", "Jane", "Jade"],
  "age": [2, 10, 3]
}

df = pd.DataFrame(data)
df

num_of_rows = len(df.index)

print(f"The number of rows is {num_of_rows}")
# The number of rows is 3
</code></pre>
<p>In the code above, we passed <code>df.index</code> as a parameter to the <code>len()</code> function. This returns the number of rows in the dataframe. </p>
<p>The difference between this example and the previous one is that we're not attaching the <code>size</code> property to <code>df.index</code>. Instead, we're using <code>df.index</code> as the <code>len()</code> function's parameter. </p>
<h2 id="heading-how-to-get-the-number-of-rows-in-a-dataframe-using-the-axes-attribute">How to Get the Number of Rows in a Dataframe Using the <code>axes</code> Attribute</h2>
<p>The <code>axes</code> attribute returns the value as the <code>index</code> attribute: <code>RangeIndex(start=0, stop=3, step=1)</code>. </p>
<p>Similarly, you can return the number of rows using either the <code>size</code> property or the <code>len()</code> function: </p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df

num_of_rows = df.axes[<span class="hljs-number">0</span>].size

print(<span class="hljs-string">f"The number of rows is <span class="hljs-subst">{num_of_rows}</span>"</span>)
<span class="hljs-comment"># The number of rows is 3</span>
</code></pre>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

data = {
  <span class="hljs-string">"name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>, <span class="hljs-string">"Jade"</span>],
  <span class="hljs-string">"age"</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>]
}

df = pd.DataFrame(data)
df

num_of_rows = len(df.axes[<span class="hljs-number">0</span>])

print(<span class="hljs-string">f"The number of rows is <span class="hljs-subst">{num_of_rows}</span>"</span>)
<span class="hljs-comment"># The number of rows is 3</span>
</code></pre>
<p>The logic in the two code blocks above is the same as those in the last section: </p>
<ul>
<li><code>df.index.size</code> returns the number of elements/rows in the dataframe. </li>
<li><code>len(df.index)</code> returns the number of rows in the dataframe. </li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about dataframes in Pandas. They are two-dimensional data structures that organize data in rows and columns. </p>
<p>We saw different methods for getting the number of rows in a dataframe. We discussed the following methods along with code examples to show their application:</p>
<ul>
<li>The <code>len()</code> function.</li>
<li>The <code>shape</code> attribute.</li>
<li>The <code>index</code> attribute.</li>
<li>The <code>axes</code> attribuite. </li>
</ul>
<p>Happy coding! You can learn more about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python End Program – How to Exit a Python Program in the Terminal ]]>
                </title>
                <description>
                    <![CDATA[ You can execute Python code in a terminal just like you would in an IDE like VS Code, Atom, and so on. You can do this in both Windows and Unix operating systems like Linux and macOS.  In this article, you'll learn how to exit a Python program in ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-end-program-how-to-exit-a-python-program-in-terminal/</link>
                <guid isPermaLink="false">66b0a340d7edba94d20b3bd0</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ terminal ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 16 May 2023 16:48:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/jake-walker-MPKQiDpMyqU-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can execute Python code in a terminal just like you would in an IDE like VS Code, Atom, and so on. You can do this in both Windows and Unix operating systems like Linux and macOS. </p>
<p>In this article, you'll learn how to exit a Python program in the terminal using the following methods:</p>
<ul>
<li>The <code>exit()</code> and <code>quit()</code> functions in Windows and macOS (and other Unix-based systems – we'll use macOS to represent them). </li>
<li>The <code>Ctrl + Z</code> command in Windows. </li>
<li>The <code>Ctrl + D</code> command in macOS. </li>
</ul>
<h2 id="heading-how-to-run-a-python-program-in-the-terminal">How to Run a Python Program in the Terminal</h2>
<p>To run Python in the terminal, you have to open your terminal and run the <code>python</code> command. </p>
<p>Note that the <code>Python</code> command will only work in your terminal if you have Python installed on your computer. </p>
<p>After running the command, you should have something like this in the terminal:</p>
<pre><code class="lang-bash">C:\Users\USER&gt;python
Python 3.10.8 (main, Nov  6 2022, 23:27:16)  [GCC 12.2.0 64 bit (AMD64)] on win32
Type <span class="hljs-string">"help"</span>, <span class="hljs-string">"copyright"</span>, <span class="hljs-string">"credits"</span> or <span class="hljs-string">"license"</span> <span class="hljs-keyword">for</span> more information.
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/py-in-terminal.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Python command in the terminal</em></p>
<p>I am using Command Prompt for Windows but this should work the same way if you're using macOS or Linux.</p>
<p>Now you can run Python code in the terminal: </p>
<pre><code class="lang-bash">&gt;&gt;&gt; <span class="hljs-built_in">print</span>(<span class="hljs-string">"Welcome to Py in the terminal!"</span>)
Welcome to Py <span class="hljs-keyword">in</span> the terminal!
</code></pre>
<h2 id="heading-how-to-exit-a-python-program-in-the-terminal-using-the-exit-and-quit-functions">How to Exit a Python Program in the Terminal Using the <code>exit()</code> and <code>quit()</code> Functions</h2>
<p>You can use the <code>exit()</code> and <code>quit()</code> functions to exit a Python program in Windows and macOS. </p>
<pre><code class="lang-bash">&gt;&gt;&gt; <span class="hljs-built_in">print</span>(<span class="hljs-string">"Welcome to Py in the terminal!"</span>)
Welcome to Py <span class="hljs-keyword">in</span> the terminal!
&gt;&gt;&gt; <span class="hljs-built_in">exit</span>()

C:\Users\USER&gt;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/py-in-terminal-exit.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>exit() command in Python terminal</em></p>
<p>In the example above, we printed "Welcome to Py in the terminal!" before exiting the terminal using the  <code>exit()</code> function. </p>
<p>After the function is executed, you'll be able to use the terminal the regular way (with the Python environment). </p>
<p>The process is the same for the <code>quit()</code> function:</p>
<pre><code class="lang-bash">&gt;&gt;&gt; <span class="hljs-built_in">print</span>(<span class="hljs-string">"Welcome to Py in the terminal!"</span>)
Welcome to Py <span class="hljs-keyword">in</span> the terminal!
&gt;&gt;&gt; quit()

C:\Users\USER&gt;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/py-in-terminal-quit.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>exit() command in Python terminal</em></p>
<h2 id="heading-how-to-exit-a-python-program-in-the-terminal-using-the-ctrl-command">How to Exit a Python Program in the Terminal Using the <code>Ctrl +</code> Command</h2>
<p>You can exit a Python program running in a Windows terminal using the <code>Ctrl + Z</code> command: </p>
<pre><code class="lang-bash">&gt;&gt;&gt; <span class="hljs-built_in">print</span>(<span class="hljs-string">"Welcome to Py in the terminal!"</span>)
Welcome to Py <span class="hljs-keyword">in</span> the terminal!
&gt;&gt;&gt; ^Z


C:\Users\USER&gt;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/py-in-terminal-ctrl-z.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>ctrl + z command to exit Python terminal in Windows</em></p>
<p>Similarly, you can use the <code>Ctrl + D</code> command in macOS. </p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about running a Python program in the terminal. </p>
<p>We saw how to run Python in the terminal using the <code>Python</code> command. </p>
<p>We also saw how to exit a Python program in the terminal using a couple different methods. </p>
<p>The <code>exit()</code> and <code>quit()</code> functions can exit a Python program in the terminal for both Windows and macOS. </p>
<p>Alternatively, you can use the <code>Ctrl + Z</code> command to exit a Python program in the terminal in Windows and <code>Ctrl + D</code> in macOS. </p>
<p>Happy coding! You can learn more about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Merge Dictionaries – Merging Two Dicts in Python ]]>
                </title>
                <description>
                    <![CDATA[ Dictionaries are one of the built-in data structures in Python. You can use them to store data in key-value pairs.  You can read about the different methods you can use to access, modify, add, and remove elements in a dictionary here.  In this articl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-merge-dictionaries-merging-two-dicts-in-python/</link>
                <guid isPermaLink="false">66b0a34b3ac4671a1e5802fa</guid>
                
                    <category>
                        <![CDATA[ dictionary ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 11 May 2023 21:51:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/hannah-busing-Zyx1bK9mqmA-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Dictionaries are one of the built-in data structures in Python. You can use them to store data in key-value pairs. </p>
<p>You can read about the different methods you can use to access, modify, add, and remove elements in a dictionary <a target="_blank" href="https://www.freecodecamp.org/news/python-dictionary-methods-dictionaries-in-python/">here</a>. </p>
<p>In this article, you'll learn how to merge two dictionaries using the following:</p>
<ul>
<li>The <code>update()</code> method.</li>
<li>The double asterisk/star operator (<code>**</code>). </li>
<li>The <code>chain()</code> method.</li>
<li>The <code>ChainMap()</code> method.</li>
<li>The merge operator (<code>|</code>).</li>
<li>The update operator (<code>|=</code>).</li>
</ul>
<h2 id="heading-how-to-merge-two-dictionaries-in-python">How to Merge Two Dictionaries in Python</h2>
<p>In this section, we'll discuss the different methods you can use to merge dictionaries in Python, along with code examples.</p>
<p>All the examples you'll see in this article will involve the merging of two dictionaries, but you can merge as many as you want.</p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-update-method">How to Merge Two Dictionaries in Python Using the <code>update()</code> Method</h3>
<p>The <code>update()</code> method is a built-in method that you can use to add data to dictionaries. </p>
<p>Consider the dictionary below:</p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

devBio.update({<span class="hljs-string">"role"</span>: <span class="hljs-string">"Technical Writer"</span>})

print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'role': 'Technical Writer'}</span>
</code></pre>
<p>In the code above, we created a dictionary called <code>devBio</code> with three key and value pairs: <code>{'name': 'Ihechikara', 'age': 50, 'language': 'Python'}</code>. </p>
<p>Using the <code>update()</code> method, we added another key and value pair: <code>devBio.update({"role": "Technical Writer"})</code>. </p>
<p>In the same manner, we can merge two dictionaries by passing another dictionary as a parameter to the <code>update()</code> method. Here's an example:</p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

devBio.update(tools)

print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we created two dictionaries — <code>devBio</code> and <code>tools</code>. </p>
<p>Using the <code>update()</code> method, we merged the key and value pairs of the <code>tools</code> dictionary to the <code>devBio</code> dictionary: <code>devBio.update(tools)</code>. </p>
<p>The merged dictionaries looked like this: </p>
<pre><code class="lang-python">{
    <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ihechikara'</span>, 
    <span class="hljs-string">'age'</span>: <span class="hljs-number">500</span>, 
    <span class="hljs-string">'language'</span>: <span class="hljs-string">'Python'</span>, 
    <span class="hljs-string">'dev environment'</span>: <span class="hljs-string">'JupyterLab'</span>, 
    <span class="hljs-string">'os'</span>: <span class="hljs-string">'Windows'</span>, 
    <span class="hljs-string">'visualization'</span>: <span class="hljs-string">'Matplotlib'</span>
}
</code></pre>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-double-asterisk-operator">How to Merge Two Dictionaries in Python Using the Double Asterisk Operator (<code>**</code>)</h3>
<p>You can use the double asterisk (also called double star) operator (<code>**</code>) to "unpack" and merge the key and value pairs of two or more dictionaries into a variable. </p>
<p>Here's a code example: </p>
<pre><code class="lang-python">devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = { **devBio, **tools}

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we unpacked the <code>devBio</code> and <code>tools</code> dictionaries using the double asterisk operator: <code>{ **devBio, **tools}</code>. </p>
<p>We then stored them in a variable called <code>merged_bio</code>. </p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-chain-method">How to Merge Two Dictionaries in Python Using the <code>chain()</code> Method</h3>
<p>The <code>chain()</code> method takes multiple iterable objects as its parameter. It merges and returns the objects as one iterable object. </p>
<p>You have to import the <code>chain()</code> method from the <code>itertools</code> module before using it: </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> chain

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = dict(chain(devBio.items(), tools.items()))

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we passed the dictionaries to be merged as parameters to the <code>chain()</code> method: <code>chain(devBio.items(), tools.items())</code>. </p>
<p>We used the <code>items()</code> method to access the key and value pairs of each dictionary. </p>
<p>Lastly, we nested the <code>chain()</code> method and its parameters in the <code>dict()</code> method: <code>dict(chain(devBio.items(), tools.items()))</code>.</p>
<p>The <code>dict()</code> method can be used to create a dictionary so we used it to convert the iterable objects returned (the key and value pairs) into a dictionary, and stored them in the <code>merged_bio</code> variable.</p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-chainmap-method">How to Merge Two Dictionaries in Python Using the <code>ChainMap()</code> Method</h3>
<p>The <code>ChainMap()</code> method works the same way as the <code>chain()</code> method as regards to merging dictionaries. The main difference is that you don't need the <code>items()</code> method to access the key and value pairs of the dictionaries. </p>
<p>You can import the <code>ChainMap()</code> method from the <code>collections</code> module. </p>
<p>Here's how you can use the <code>ChainMap()</code> method to merger two dictionaries:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> ChainMap

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = dict(ChainMap(devBio, tools))

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>You can check the explanation in the last section to understand the logic in the code above. </p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-merge-operator">How to Merge Two Dictionaries in Python Using the Merge Operator (<code>|</code>)</h3>
<p>The merge operator (<code>|</code>) was first introduced in Python 3.9. It's a shorter and simpler syntax that you can use to merge dictionaries. </p>
<p>Here's an example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> ChainMap

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

merged_bio = devBio | tools

print(merged_bio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 500, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>So to merge the <code>devBio</code> and <code>tools</code> dictionary, we put the <code>|</code> operator between them:  <code>devBio | tools</code>.</p>
<h3 id="heading-how-to-merge-two-dictionaries-in-python-using-the-update-operator">How to Merge Two Dictionaries in Python Using the Update Operator (<code>|=</code>)</h3>
<p>The update operator (<code>|=</code>) operator is another operator that was introduced in Python 3.9. </p>
<p>It works just like the <code>update()</code> method. That is: </p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> ChainMap

devBio = {
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ihechikara"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-number">500</span>,
  <span class="hljs-string">"language"</span>: <span class="hljs-string">"Python"</span>
}

tools = {
  <span class="hljs-string">"dev environment"</span>: <span class="hljs-string">"JupyterLab"</span>,
  <span class="hljs-string">"os"</span>: <span class="hljs-string">"Windows"</span>,
  <span class="hljs-string">"visualization"</span>: <span class="hljs-string">"Matplotlib"</span>
}

devBio |= tools

print(devBio)
<span class="hljs-comment"># {'name': 'Ihechikara', 'age': 50, 'language': 'Python', 'dev environment': 'JupyterLab', 'os': 'Windows', 'visualization': 'Matplotlib'}</span>
</code></pre>
<p>In the code above, we used the <code>|=</code> to mege the key and value pairs in the <code>tools</code> dictionary into the <code>devBio</code> dictionary.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about dictionaries in Python. You can use them to store data in key-value pairs. </p>
<p>We saw how to merge two dictionaries in Python using:</p>
<ul>
<li>The <code>update()</code> method.</li>
<li>The double asterisk/star operator (<code>**</code>). </li>
<li>The <code>chain()</code> method.</li>
<li>The <code>ChainMap()</code> method.</li>
<li>The merge operator (<code>|</code>).</li>
<li>The update operator (<code>|=</code>).</li>
</ul>
<p>Each method had its own section with code examples that showed how to use them to merge dictionaries. </p>
<p>Happy coding! You can learn more about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ xor.py – How the Python XOR Operator Works ]]>
                </title>
                <description>
                    <![CDATA[ You can use bitwise operators in Python to perform different operations on the individual bits of an integer.  There are different bitwise operators like the bitwise AND (&), bitwise OR (|), bitwise XOR (^), and so on.  In this article, we'll focus o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/xor-py-how-the-python-xor-operator-works/</link>
                <guid isPermaLink="false">66b0a3947cd8dca6718a2265</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 08 May 2023 16:35:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/xor-in-python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use bitwise operators in Python to perform different operations on the individual bits of an integer. </p>
<p>There are different bitwise operators like the bitwise AND (<code>&amp;</code>), bitwise OR (<code>|</code>), bitwise XOR (<code>^</code>), and so on. </p>
<p>In this article, we'll focus on the bitwise XOR (<code>^</code>) operator. You'll learn about its mode of operation along with some practical examples. </p>
<h2 id="heading-how-the-python-xor-operator-works">How the Python XOR Operator Works</h2>
<p>The XOR operator first converts the integers involved in the operation to their binary format. The operator then evaluates the corresponding bits of the binary values.</p>
<p>When two bits are evaluated, the value returned will be dependent on the bits. If both bits are 0, 0 is returned. If both bits are 1, 0 is returned. If either of the bits is 1 while the other is 0 then 1 will be returned. </p>
<p>So the XOR operator will only return 1 when two bits have different values. That is: </p>
<p>0 ^ 0 = 0.<br>1 ^ 1 = 0.<br>1 ^ 0 = 1.<br>0 ^ 1 = 1.</p>
<p>After evaluating all the corresponding bits, the resulting binary value will be returned in base 10. </p>
<p>Don't worry if the explanations above seem confusing – the examples in the next section should simplify how the XOR operator works.</p>
<h2 id="heading-python-xor-operator-example">Python XOR Operator Example</h2>
<p>In this section, you'll see code examples that show how the bitwise XOR operator works. </p>
<pre><code class="lang-python">x = <span class="hljs-number">12</span>
y = <span class="hljs-number">10</span>

print(x ^ y)
<span class="hljs-comment"># 6</span>
</code></pre>
<p>In the code above, we created two variables <code>x</code> and <code>y</code> with 12 and 10 as their respective values. </p>
<p>Using the XOR operator — <code>x ^ y</code> — we got 6 returned. </p>
<p>Let's break the code down to see how we got a value of 6 from the operation.</p>
<h3 id="heading-step-1-conversion-to-binary-values">Step #1 - Conversion to Binary Values</h3>
<p>We started with two values (12 and 10):</p>
<pre><code class="lang-python">x = <span class="hljs-number">12</span>
y = <span class="hljs-number">10</span>
</code></pre>
<p>These values have to be converted to their binary format by the XOR operator before the operations starts. </p>
<p>The binary value of 12 is 1100 while the binary value of 10 is 1010. </p>
<h3 id="heading-step-2-evaluating-corresponding-bits">Step #2 - Evaluating Corresponding Bits</h3>
<p>Now that the values have been converted to their binary formats, the next thing that the XOR operator does is to compare corresponding bits. </p>
<p>So the first bit in 1100 will be compared to the first bit in 1010. The second bit in both binary values will be compared next. This comparison will continue until there are no bits left to compare. </p>
<p>Recall that we discussed how the XOR operator returns a value from each comparison: </p>
<p>0 ^ 0 = 0.<br>1 ^ 1 = 0.<br>1 ^ 0 = 1.<br>0 ^ 1 = 1.</p>
<p>Using the logic above, lets compare the bits in both operands — 1100 and 1010. We'll denote them as operand A and B, respectively.</p>
<p>Operand A's first bit value = 1. Operand B's first bit value = 1.<br>1 ^ 1 = 0. </p>
<p>Operand A's second bit value = 1. Operand B's second bit value = 0.<br>1 ^ 0 = 1. </p>
<p>Operand A's third bit value = 0. Operand B's third bit value = 1.<br>0 ^ 1 = 1. </p>
<p>Operand A's fourth bit value = 0. Operand B's fourth bit value = 0.<br>0 ^ 0 = 0. </p>
<p>When we collect the resulting values from each comparison, we have 0110 which is the same as 6 in base 10. </p>
<p>The bit comparisons above explain how the code in the last section returned a value of 6. That is:</p>
<pre><code class="lang-python">x = <span class="hljs-number">12</span>
y = <span class="hljs-number">10</span>

print(x ^ y)
<span class="hljs-comment"># 6</span>
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about bitwise operators in Python. They are used to perform operations involving the individual bits of integers. </p>
<p>We talked about the bitwise XOR (<code>^</code>) operator which converts integers to their binary format, and the compares their corresponding bit values. </p>
<p>We saw an example that showed how the XOR operator works under the hood. </p>
<p>Happy coding! You can learn more about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Parse a String in Python – Parsing Strings Explained ]]>
                </title>
                <description>
                    <![CDATA[ Parsing a string can mean different things in Python. You can parse a string by splitting or extracting the substrings.  You can also parse a string by converting it to an integer or float variable. Although this should be categorized as a type conve... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-parse-a-string-in-python/</link>
                <guid isPermaLink="false">66b0a2dc3dc92ea6a5a091e7</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Thu, 04 May 2023 21:04:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/split-and-split-methods-in-python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Parsing a string can mean different things in Python. You can parse a string by splitting or extracting the substrings. </p>
<p>You can also parse a string by converting it to an integer or float variable. Although this should be categorized as a type conversion operation, you'll come across resources that refer to it as string parsing. </p>
<p>In this article, you'll learn how to parse a string using the <code>split()</code> and <code>strip()</code> methods. You'll also learn how to convert a string to an integer using the <code>int()</code> function.</p>
<h2 id="heading-how-to-parse-a-string-in-python-using-the-split-method">How To Parse a String in Python Using the <code>split()</code> Method</h2>
<p>You can use the <code>split()</code> method in Python to "split" substrings of a string into a list. </p>
<p>Here's what the parameter looks like: </p>
<pre><code class="lang-txt">string.split(separator, maxsplit)
</code></pre>
<p>The <code>split()</code> method has two optional parameters:</p>
<ul>
<li><code>separator</code> specifies where to start splitting from (you'll understand this better with the examples in the next section). </li>
<li><code>maxsplit</code> specifies the maximum number of splits. </li>
</ul>
<h3 id="heading-split-method-example-1-how-to-use-the-separator-parameter"><code>split()</code> Method Example #1 - How To Use the Separator Parameter</h3>
<pre><code class="lang-python">favorite_languages = <span class="hljs-string">"JavaScript, Python, and Java"</span>

lang_split = favorite_languages.split(<span class="hljs-string">","</span>)

print(lang_split)
<span class="hljs-comment"># ['JavaScript', ' Python', ' and Java']</span>
</code></pre>
<p>In the example above, we created a string called <code>favorite_languages</code> which had three substrings: "JavaScript, Python, and Java". </p>
<p>Using the <code>split()</code> method, we specified that each substring should be split after each comma in the string: <code>favorite_languages.split(",")</code>. </p>
<p>The result was a list of each substring: ['JavaScript', ' Python', ' and Java']. </p>
<p>This example shows how to use the first parameter of the <code>split()</code> method. The next example will help you understand the second parameter. </p>
<h3 id="heading-split-method-example-2-how-to-use-the-maxsplit-parameter"><code>split()</code> Method Example #2 - How To Use the Maxsplit Parameter</h3>
<pre><code class="lang-python">favorite_languages = <span class="hljs-string">"JavaScript, Python, and Java"</span>

lang_split = favorite_languages.split(<span class="hljs-string">","</span>, <span class="hljs-number">1</span>)

print(lang_split)
<span class="hljs-comment"># ['JavaScript', ' Python, and Java']</span>
</code></pre>
<p>In the code above, we made use of the <code>maxsplit</code> parameter which specifies the number of splits to be performed. </p>
<p>So <code>favorite_languages.split(",", 1)</code> means that only one substring should be split, while the rest would remain as they were in the original string. </p>
<p>In the output of the code, only JavaScript was split, while Python and Java retained their initial positions in the string. That is: <code>['JavaScript', ' Python, and Java']</code>. </p>
<h2 id="heading-how-to-parse-a-string-in-python-using-the-strip-method">How To Parse a String in Python Using the <code>strip()</code> Method</h2>
<p>You can use the <code>strip()</code> method to remove white spaces or specified characters in a string.</p>
<p>Here's what the syntax looks like:</p>
<pre><code class="lang-python">string.strip([chars])
</code></pre>
<p>The <code>chars</code> parameter specifies the set of characters to be removed. This parameter is optional, so leaving the parenthesis empty will only remove white spaces. </p>
<p>Let's see some examples.</p>
<h3 id="heading-strip-method-example-1"><code>strip()</code> Method Example #1</h3>
<pre><code class="lang-python">username = <span class="hljs-string">"       Doe      "</span>

user = username.strip()

print(user) 
<span class="hljs-comment"># Doe</span>
</code></pre>
<p>In the example above, we had a string with leading and trailing whitespace characters: "       Doe      ". </p>
<p>Using the strip method without any parameter, we got rid of the whitespaces: <code>username.strip()</code>. </p>
<p>In the next example, we'll pass in parameters to the <code>strip()</code> method. </p>
<h3 id="heading-strip-method-example-2"><code>strip()</code> Method Example #2</h3>
<p>In this section, we'll use a string that has different characters in it that aren't whitespaces: </p>
<pre><code class="lang-python">username = <span class="hljs-string">"=+---Doe---+="</span>
</code></pre>
<p>The goal here is to get rid of the unwanted characters (=+-) found in the <code>username</code> variable.</p>
<p>If you use the <code>strip()</code> method without any parameters, it won't get rid of those characters. Without parameters, the <code>strip()</code> method only removes whitespaces. </p>
<p>To remove the characters in the string, you have to use them as a parameter to tell the <code>strip()</code> method that they should be removed. That is: </p>
<pre><code class="lang-python">username = <span class="hljs-string">"=+---Doe---+="</span>

user = username.strip(<span class="hljs-string">"=+-"</span>)

print(user) 
<span class="hljs-comment"># Doe</span>
</code></pre>
<p>In the code above, we passed in the characters to be removed from the string as a parameter to the <code>strip()</code> method: <code>username.strip("=+-")</code>. </p>
<p>Note that you have to nest those characters in quotation marks ("=+-").</p>
<h2 id="heading-how-to-convert-a-string-to-an-integer-using-the-int-function">How To Convert a String to an Integer Using the <code>int()</code> Function</h2>
<p>Data type conversion helps you perform certain operations that involve incompatible data types. </p>
<p>For instance, the example below shows what happens when you try to add an integer and a string: </p>
<pre><code class="lang-python">age = <span class="hljs-string">"300"</span>

print(age + <span class="hljs-number">300</span>) 
<span class="hljs-comment"># TypeError: can only concatenate str (not "int") to str</span>
</code></pre>
<p>In the code above, we created a string value with a value of "300". When we tried adding it to an integer value of 300, we got an error.</p>
<p>The error is thrown because the compiler assumes we're trying to add two strings. <a target="_blank" href="https://www.freecodecamp.org/news/python-concatenate-strings-how-to-combine-and-append-strings-in-python/">String concatenation in Pytho</a>n cannot be performed using a string and an integer. </p>
<p>To solve this problem, you can convert the string to an integer before using it in a mathematical operation. </p>
<p>Here's how you can do that using the <code>int()</code> function:</p>
<pre><code class="lang-python">age = <span class="hljs-string">"300"</span>

age_to_int = int(age)

print(age_to_int + <span class="hljs-number">300</span>) 
<span class="hljs-comment"># 600</span>
</code></pre>
<p>In the code above, we used the <code>int()</code> function to convert the <code>age</code> string to an integer: <code>int(age)</code>. </p>
<p>Now, you're to use the variable as an integer. </p>
<p>A common use case for converting from a string to an integer is seen when getting input from a user. You can see an example like that in <a target="_blank" href="https://www.freecodecamp.org/news/python-convert-string-to-int-how-to-cast-a-string-in-python/#:~:text=A%20practical%20example%20of%20converting%20a%20string%20to%20an%20int">this article</a>.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about parsing strings in Python. </p>
<p>We saw examples that showed how to parse a string using the <code>split()</code> and <code>strip()</code> methods. </p>
<p>We also saw how to convert a string to an integer using the <code>int()</code> function. </p>
<p>Happy coding! I also write about Python on <a target="_blank" href="https://ihechikara.com/">my blog</a>. </p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
