<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rumeysa Layık on Medium]]></title>
        <description><![CDATA[Stories by Rumeysa Layık on Medium]]></description>
        <link>https://medium.com/@rumeysalayik?source=rss-ff9787923c7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1lohLyAigmlqD5aDz2rSrQ.jpeg</url>
            <title>Stories by Rumeysa Layık on Medium</title>
            <link>https://medium.com/@rumeysalayik?source=rss-ff9787923c7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:57:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rumeysalayik/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My Autodidactic Journey into FPGA Programming-Day 6]]></title>
            <link>https://medium.com/@rumeysalayik/my-autodidactic-journey-into-fpga-programming-day-6-c1375be13da9?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1375be13da9</guid>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 20:00:29 GMT</pubDate>
            <atom:updated>2026-03-31T20:00:29.006Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everybody, I solved the problem which is mentioned in the previous blog post.</p><p>The last state of the modules are shown in the following code pieces:</p><pre>module uart_tx (<br>    input clk,<br>    input [7:0] tx_data,<br>    input tx_start,<br>    output reg tx_pin,<br>    output reg busy<br>);<br><br>    parameter BAUD_DIV = 27000000 / 115200; // 234<br><br>    localparam IDLE=0, START=1, DATA=2, STOP=3;<br>    reg [1:0] state = IDLE;<br>    reg [7:0] baud_counter = 0;<br>    reg [2:0] bit_index = 0;<br>    reg [7:0] shifter;<br><br>    always @(posedge clk) begin<br>        case (state)<br>            IDLE: begin<br>                tx_pin &lt;= 1;<br>                busy &lt;= 0;<br>                if (tx_start) begin<br>                    shifter &lt;= tx_data;<br>                    state &lt;= START;<br>                    busy &lt;= 1;<br>                    baud_counter &lt;= 0;<br>                end<br>            end<br>            START: begin<br>                tx_pin &lt;= 0; // Start biti<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= DATA;<br>                    bit_index &lt;= 0;<br>                end else baud_counter &lt;= baud_counter + 1;<br>            end<br>            DATA: begin<br>                tx_pin &lt;= shifter[bit_index];<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    if (bit_index == 7) state &lt;= STOP;<br>                    else bit_index &lt;= bit_index + 1;<br>                end else baud_counter &lt;= baud_counter + 1;<br>            end<br>            STOP: begin<br>                tx_pin &lt;= 1; // Stop biti<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    state &lt;= IDLE;<br>                end else baud_counter &lt;= baud_counter + 1;<br>            end<br>        endcase<br>    end<br>endmodule</pre><pre>module uart_rx (<br>    input clk,<br>    input rx_pin,<br>    output reg [7:0] rx_data,<br>    output reg rx_done<br>);<br><br>    parameter BAUD_DIV = 27000000 / 115200;<br><br>    localparam IDLE=0, START=1, DATA=2, STOP=3;<br>    reg [1:0] state = IDLE;<br>    reg [7:0] baud_counter = 0;<br>    reg [2:0] bit_index = 0;<br>    reg [7:0] shift_reg;<br><br>    always @(posedge clk) begin<br>        case (state)<br>            IDLE: begin<br>                rx_done &lt;= 0;<br>                if (rx_pin == 0) begin // Start biti düştü<br>                    state &lt;= START;<br>                    baud_counter &lt;= 0;<br>                end<br>            end<br>            START: begin<br>                // Sinyalin TAM ORTASINA gitmek için yarım bit bekle<br>                if (baud_counter == (BAUD_DIV/2) - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= DATA;<br>                    bit_index &lt;= 0;<br>                end else baud_counter &lt;= baud_counter + 1;<br>            end<br>            DATA: begin<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    shift_reg[bit_index] &lt;= rx_pin;<br>                    if (bit_index == 7) state &lt;= STOP;<br>                    else bit_index &lt;= bit_index + 1;<br>                end else baud_counter &lt;= baud_counter + 1;<br>            end<br>            STOP: begin<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    rx_data &lt;= shift_reg;<br>                    rx_done &lt;= 1;<br>                    state &lt;= IDLE;<br>                end else baud_counter &lt;= baud_counter + 1;<br>            end<br>        endcase<br>    end<br>endmodule</pre><pre>module top (<br>    input clk,<br>    input uart_rx_usb,<br>    output uart_tx_usb,<br>    output reg led<br>);<br><br>    wire [7:0] rx_byte;<br>    wire rx_ready;<br>    reg [7:0] tx_byte;<br>    reg tx_trigger = 0;<br>    wire tx_busy;<br><br>    reg [24:0] beacon_timer = 0; // 1 saniyelik sayaç<br>    reg [15:0] trigger_timer = 0;<br><br>    uart_rx my_rx (.clk(clk), .rx_pin(uart_rx_usb), .rx_data(rx_byte), .rx_done(rx_ready));<br>    uart_tx my_tx (.clk(clk), .tx_data(tx_byte), .tx_start(tx_trigger), .tx_pin(uart_tx_usb), .busy(tx_busy));<br><br>    always @(posedge clk) begin<br>        // --- 1. Saniyede Bir &quot;!&quot; (Sistem Hayatta mı Testi) ---<br>        beacon_timer &lt;= beacon_timer + 1;<br>        if (beacon_timer == 27000000) begin <br>            beacon_timer &lt;= 0;<br>            tx_byte &lt;= 8&#39;h21; // &#39;!&#39;<br>            tx_trigger &lt;= 1;<br>            trigger_timer &lt;= 2000;<br>        end<br><br>        // --- 2. ASIL İŞLEM: Rakamı 2 ile Çarp ---<br>        if (rx_ready) begin<br>            // Sadece rakam gelirse çarpma yap, yoksa olduğu gibi gönder<br>            if (rx_byte &gt;= 8&#39;h30 &amp;&amp; rx_byte &lt;= 8&#39;h39) begin<br>                tx_byte &lt;= ((rx_byte - 8&#39;h30) * 2) + 8&#39;h30;<br>            end else begin<br>                tx_byte &lt;= rx_byte;<br>            end<br>            <br>            trigger_timer &lt;= 2000;<br>            led &lt;= ~led;<br>        end <br><br>        // --- 3. Tetik Yönetimi ---<br>        if (trigger_timer &gt; 0) begin<br>            trigger_timer &lt;= trigger_timer - 1;<br>            tx_trigger &lt;= 1;<br>        end else begin<br>            tx_trigger &lt;= 0;<br>        end<br>    end<br>endmodule</pre><p>I will explain all details tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1375be13da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Autodidactic Journey into FPGA Programming-Day 5]]></title>
            <link>https://medium.com/@rumeysalayik/my-autodidactic-journey-into-fpga-programming-day-5-a4c3ff08378c?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c3ff08378c</guid>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 20:56:08 GMT</pubDate>
            <atom:updated>2026-03-30T20:56:08.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>FPGA Diaries: Hitting the “IO Bank Voltage” Wall</h3><p>Today was a masterclass in why FPGA development is as much about electrical engineering as it is about coding. What started as a simple UART “Ping-Pong” project on a Tang Nano 9K turned into a multi-hour battle against a stubborn hardware constraint.</p><h4>The Problem: ERROR (CT1136) — Bank 3 VCCIO Conflict</h4><p>In the world of software, a syntax error is annoying. In the world of FPGAs, a “Bank Conflict” is a brick wall. The issue arose when I tried to use the onboard LED (Pin 10) alongside the system clock (Pin 52) and UART pins.</p><p><strong>The Culprit:</strong> FPGA pins are grouped into “Banks.” On the Tang Nano 9K, Bank 3 can sometimes default to a 1.8V logic level. When I forced the UART pins (17 and 18) to operate at 3.3V (LVCMOS33), the IDE threw a fit. You cannot have two different supply voltages (VCCIO) powering the same bank simultaneously. It’s an “all or nothing” deal.</p><h4>The Battle with Gowin IDE</h4><p>Even after changing the “Unused Pin” configurations in the GUI, the error persisted. I learned that sometimes you have to bypass the interface and speak directly to the hardware via the .cst (Constraint) file.</p><p><strong>Tactics Used:</strong></p><ol><li><strong>Voltage Segregation:</strong> We manually assigned the Clock and LED to a 1.8V standard while keeping the UART on 3.3V, essentially “negotiating” a peace treaty between the banks.</li><li><strong>The Invisible Trigger:</strong> On the logic side, the FPGA was <em>too</em> fast. My transmit trigger was only lasting 37 nanoseconds (one clock cycle at 27MHz). The PC couldn’t even “hear” the start signal. We implemented a handshake-style timer to hold the trigger until the UART module confirmed it was busy.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*4aFhUJpa8mg-qA0Epg9V0Q.png" /></figure><p>I will try to solve this problem…🤞</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c3ff08378c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Autodidactic Journey into FPGA Programming-Day 4]]></title>
            <link>https://medium.com/@rumeysalayik/my-autodidactic-journey-into-fpga-programming-day-4-bd9a05a74bd4?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd9a05a74bd4</guid>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 20:33:11 GMT</pubDate>
            <atom:updated>2026-03-29T20:33:11.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Yesterday, we discussed the mathematical foundation of the UART protocol and that famous 234-cycle rhythm. Today, I translated that theory into Verilog lines and uploaded it to my Tang Nano 9K board. For a software engineer, the most exciting moment isn’t just seeing a code output on a screen, but seeing it “bend time” in the physical world to communicate with another device.</p><p>First, we tamed the 27 MHz clock with a <strong>Baud Rate Generator</strong>. Then, we “serialized” the data by building a <strong>State Machine</strong>. Seeing the PuTTY screen fill with infinite “A”s the moment I pressed the button was my first victory in the hardware world. But the real surprise came later: I built a system that doesn’t just talk, but also listens. I managed to control the onboard LED using ‘1’ and ‘0’ commands sent from my keyboard.</p><p>The most critical thing I learned during this process was that UART is not just a cable, but a very precise piece of timing engineering. Especially on the receiver (RX) side, sampling the data exactly at its “center point” (the $1/2$ bit wait rule) is the key to error-free communication.</p><pre>//uart_tx.v<br>module uart_tx (<br>    input clk,              <br>    input [7:0] tx_data,     <br>    input tx_start,          <br>    output reg tx_pin,       <br>    output reg busy          <br>);<br>    parameter CLK_FREQ = 27000000;<br>    parameter BAUD_RATE = 115200;<br>    parameter BAUD_DIV = CLK_FREQ / BAUD_RATE; // Yaklaşık 234<br><br>    localparam IDLE  = 2&#39;b00;<br>    localparam START = 2&#39;b01;<br>    localparam DATA  = 2&#39;b10;<br>    localparam STOP  = 2&#39;b11;<br><br>    reg [1:0] state = IDLE;<br>    reg [7:0] baud_counter = 0;<br>    reg [2:0] bit_index = 0;<br>    reg [7:0] data_shifter;<br><br>    always @(posedge clk) begin<br>        case (state)<br>            IDLE: begin<br>                tx_pin &lt;= 1;<br>                busy &lt;= 0;<br>                if (tx_start) begin<br>                    state &lt;= START;<br>                    data_shifter &lt;= tx_data;<br>                    busy &lt;= 1;<br>                    baud_counter &lt;= 0;<br>                end<br>            end<br><br>            START: begin<br>                tx_pin &lt;= 0;<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= DATA;<br>                    bit_index &lt;= 0;<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br><br>            DATA: begin<br>                tx_pin &lt;= data_shifter[bit_index];<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    if (bit_index == 7) begin<br>                        state &lt;= STOP;<br>                    end else begin<br>                        bit_index &lt;= bit_index + 1;<br>                    end<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br><br>            STOP: begin<br>                tx_pin &lt;= 1;<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= IDLE;<br>                    busy &lt;= 0;<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br>        endcase<br>    end<br>endmodule</pre><pre>//uart_rx<br>module uart_rx (<br>    input clk,<br>    input rx_pin,<br>    output reg [7:0] rx_data,<br>    output reg rx_done       // Bir paket başarıyla alındığında 1 olur<br>);<br><br>    parameter CLK_FREQ = 27000000;<br>    parameter BAUD_RATE = 115200;<br>    parameter BAUD_DIV = CLK_FREQ / BAUD_RATE;<br><br>    localparam IDLE  = 2&#39;b00;<br>    localparam START = 2&#39;b01;<br>    localparam DATA  = 2&#39;b10;<br>    localparam STOP  = 2&#39;b11;<br><br>    reg [1:0] state = IDLE;<br>    reg [7:0] baud_counter = 0;<br>    reg [2:0] bit_index = 0;<br>    reg [7:0] shift_reg;<br><br>    always @(posedge clk) begin<br>        case (state)<br>            IDLE: begin<br>                rx_done &lt;= 0;<br>                baud_counter &lt;= 0;<br>                if (rx_pin == 0) begin // Start bit yakalandı!<br>                    state &lt;= START;<br>                end<br>            end<br><br>            START: begin<br>                // Yarım bit süresi bekle (Ortaya gitmek için)<br>                if (baud_counter == (BAUD_DIV / 2) - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= DATA;<br>                    bit_index &lt;= 0;<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br><br>            DATA: begin<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    shift_reg[bit_index] &lt;= rx_pin; // Tam ortada örneği al!<br>                    if (bit_index == 7) begin<br>                        state &lt;= STOP;<br>                    end else begin<br>                        bit_index &lt;= bit_index + 1;<br>                    end<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br><br>            STOP: begin<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    rx_data &lt;= shift_reg;<br>                    rx_done &lt;= 1; // Paket hazır!<br>                    state &lt;= IDLE;<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br>        endcase<br>    end<br>endmodule</pre><pre>//top.v<br>module top (<br>    input clk,<br>    input btn1,            <br>    input uart_rx_usb,      <br>    output uart_tx_usb,      <br>    output reg led           <br>);<br><br>    // --- TRANSMITTER ---<br>    uart_tx my_transmitter (<br>        .clk(clk),<br>        .tx_data(8&#39;h41),      <br>        .tx_start(!btn1),<br>        .tx_pin(uart_tx_usb),<br>        .busy()<br>    );<br><br>    // --- RECEIVER---<br>    wire [7:0] received_byte;<br>    wire rx_ready;<br><br>    uart_rx my_receiver (<br>        .clk(clk),<br>        .rx_pin(uart_rx_usb),<br>        .rx_data(received_byte),<br>        .rx_done(rx_ready)<br>    );<br><br>    // --- LOGIC ---<br>    always @(posedge clk) begin<br>        if (rx_ready) begin<br>            if (received_byte == 8&#39;h31)      // &#39;1&#39;<br>                led &lt;= 0; <br>            else if (received_byte == 8&#39;h30) // &#39;0&#39; <br>                led &lt;= 1; <br>        end<br>    end<br><br>endmodule</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd9a05a74bd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Autodidactic Journey into FPGA Programming-Day 3]]></title>
            <link>https://medium.com/@rumeysalayik/yesterday-we-learnt-lots-of-things-about-uart-but-its-not-enough-to-just-read-about-uart-we-must-8656bc0f9e49?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8656bc0f9e49</guid>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 20:50:20 GMT</pubDate>
            <atom:updated>2026-03-29T20:25:17.751Z</atom:updated>
            <content:encoded><![CDATA[<p>Yesterday, we learnt lots of things about UART but it’s not enough to just read about UART; we must also imagine how to build it inside the FPGA. I will use these two main structures when I translate yesterday’s theory into code today:</p><p><strong>Baud Rate Generator (The Rhythm Master):</strong> A counter that divides the 27 MHz clock into 115,200. It will “tick” every 234 cycles and set the rhythm of the system.</p><p><strong>TX State Machine (The Transmitter):</strong> A “State Machine” similar to a switch-case structure in software:</p><ul><li><strong>IDLE:</strong> Wait.</li><li><strong>START:</strong> Pull the line to 0 (for 234 cycles).</li><li><strong>DATA:</strong> Send each of the 8 bits sequentially (234 cycles each).</li><li><strong>STOP:</strong> Pull the line back to 1.</li></ul><p>This structure will act as a “Serializer,” funneling the internal 8-lane data bus into a single wire.</p><p>Lets code Tx module.</p><pre>module uart_tx (<br>    input clk,               <br>    input [7:0] tx_data,     <br>    input tx_start,          <br>    output reg tx_pin,       <br>    output reg busy          <br>);<br><br>    parameter CLK_FREQ = 27000000;<br>    parameter BAUD_RATE = 115200;<br>    parameter BAUD_DIV = CLK_FREQ / BAUD_RATE;<br><br>    // Durum Tanımları<br>    localparam IDLE  = 2&#39;b00;<br>    localparam START = 2&#39;b01;<br>    localparam DATA  = 2&#39;b10;<br>    localparam STOP  = 2&#39;b11;<br><br>    reg [1:0] state = IDLE;<br>    reg [7:0] baud_counter = 0;<br>    reg [2:0] bit_index = 0;<br>    reg [7:0] data_shifter; <br><br>    always @(posedge clk) begin<br>        case (state)<br>            IDLE: begin<br>                tx_pin &lt;= 1; <br>                busy &lt;= 0;<br>                if (tx_start) begin<br>                    state &lt;= START;<br>                    data_shifter &lt;= tx_data;<br>                    busy &lt;= 1;<br>                    baud_counter &lt;= 0;<br>                end<br>            end<br><br>            START: begin<br>                tx_pin &lt;= 0;<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= DATA;<br>                    bit_index &lt;= 0;<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br><br>            DATA: begin<br>                tx_pin &lt;= data_shifter[bit_index];<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    if (bit_index == 7) begin<br>                        state &lt;= STOP;<br>                    end else begin<br>                        bit_index &lt;= bit_index + 1;<br>                    end<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br><br>            STOP: begin<br>                tx_pin &lt;= 1;<br>                if (baud_counter == BAUD_DIV - 1) begin<br>                    baud_counter &lt;= 0;<br>                    state &lt;= IDLE;<br>                    busy &lt;= 0;<br>                end else begin<br>                    baud_counter &lt;= baud_counter + 1;<br>                end<br>            end<br>        endcase<br>    end<br>endmodule</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8656bc0f9e49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Autodidactic Journey into FPGA Programming-Day 2]]></title>
            <link>https://medium.com/@rumeysalayik/my-autodidactic-journey-into-fpga-programming-day-2-3d87c697a911?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d87c697a911</guid>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 20:55:11 GMT</pubDate>
            <atom:updated>2026-03-27T20:55:11.865Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m on the second day of my FPGA journey, and things are getting a bit more serious. Yesterday, we simply said “hello” to the hardware world by blinking some LEDs. But at some point, just lighting up an LED isn’t enough; the board needs to tell us what’s happening inside — it needs to “talk” to us. That’s exactly when I met the legendary protocol that quietly runs inside almost every electronic device: <strong>UART (Universal Asynchronous Receiver-Transmitter).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSN8L4_j9P9mTZGWEumzDA.png" /><figcaption>UART protocol between two devices</figcaption></figure><p>In most communication protocols, there is a dedicated “Clock” wire between the transmitter and the receiver. This clock signal acts like a drumbeat, telling the receiver exactly when to read the data. However, in UART, this wire doesn’t exist.</p><ul><li><strong>Dancing Without a Drummer:</strong> Since there is no shared clock, both sides must agree on the “speed” beforehand. This is what we call the <strong>Baud Rate</strong>. If I am sending 115,200 bits per second, you must be reading exactly 115,200 bits per second.</li><li><strong>The Margin of Error:</strong> If my clock is slightly faster and yours is slightly slower, the synchronization will drift after a few bits, and the data will turn into “garbage.” This is why timing precision is everything in UART.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxqgAdY6AnL0rxTlA586Zg.png" /></figure><p>When we send an A character in software, what shape does it take over that single electrical cable?</p><p>In reality, UART packages the data into small packets (<strong>Frames</strong>) with a clear beginning and end. Each packet whispers “1”s and “0”s to the receiver by changing the voltage level of the line with a specific rhythm (the Baud Rate).</p><h4>Why is the Line Always “High” (1) While Idle?</h4><p>You might have noticed something in the diagram: Why does the line stay at a <strong>High (1)</strong> level when no data is being sent? From a software perspective, you might think, “Let’s save energy and keep it at 0,&quot; but in hardware, this is a critical safety feature.</p><ul><li><strong>Is the Cable Broken?</strong> If the line were 0 while idle, we couldn&#39;t distinguish between &quot;silence&quot; and a broken wire. However, since it is always 1, if the signal suddenly drops to 0 and stays there, the FPGA knows immediately: &quot;The connection is lost!&quot;</li><li><strong>Detecting the Start Bit:</strong> Keeping the line at a constant 1 ensures that the very first drop to 0 (the Start Bit) is detected with absolute clarity.</li></ul><h4>Anatomy of a Packet — Start, Data, and Stop</h4><p>Every character (usually 1 Byte) sent over UART is placed inside a small “envelope” called a <strong>“Data Frame.”</strong> A standard UART packet is arranged in the following sequence:</p><ol><li><strong>Start Bit (Always 0):</strong> The famous drop we just mentioned. The moment the line goes from 1 to 0, the receiver says, &quot;Okay, starting my timer.&quot; This bit always lasts for exactly one bit period.</li><li><strong>Data Bits (Usually 8 Bits):</strong> This is where our actual data lives. But there’s a fascinating detail here: <strong>LSB (Least Significant Bit) First</strong>. The rightmost bit of your data is the first one to hit the wire. If you are sending 10000001, the receiver sees the first 1 at the beginning and the last 1 at the very end.</li><li><strong>Stop Bit (Always 1):</strong> After the data bits, the line is pulled back to the 1 level. This sends a message to the receiver: &quot;The packet is over; you can go back to resting and wait for the next one.&quot; It restores the line to its &quot;Idle&quot; state.</li></ol><h4>Sampling</h4><p>Since UART is asynchronous, we don’t have a shared clock (no drummer). So, how does the FPGA know exactly where it is within the incoming data? What if there’s noise on the line?</p><ul><li><strong>The Danger of Edges:</strong> When a bit transitions from 0 to 1, it’s not instantaneous. It takes a tiny bit of time for the voltage to rise. If you try to read the data exactly at this &quot;edge,&quot; there&#39;s a high chance you&#39;ll get a wrong or unstable value.</li><li><strong>The 1/2 Bit Rule:</strong> The moment the FPGA detects the Start Bit (the drop from 1 to 0), it starts its internal timer. But it doesn’t read immediately. It waits for <strong>exactly half (1/2) of a bit period</strong>.</li><li><strong>Why?</strong> Because this delay puts us right in the <strong>middle of the bit</strong>. This is the most stable and reliable point of the signal. Once we find this first center point, we simply wait <strong>one full bit period</strong> at a time to sample the heart of all subsequent bits.</li></ul><p>Today, we discovered that UART is not just a cable; it is actually a very precise piece of timing engineering. Understanding how two devices meet in the “same rhythm” without a shared clock signal is the cornerstone of hardware programming. Tomorrow, we will translate this theory into Verilog code and bring our first <strong>Baud Rate Generator</strong> module to life. Stay tuned!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*256HX0MxAJAyPbdgb8MmLw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d87c697a911" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Autodidactic Journey into FPGA Programming-Day 1]]></title>
            <link>https://medium.com/@rumeysalayik/my-autodidactic-journey-into-fpga-programming-6043fea949ed?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6043fea949ed</guid>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 20:59:41 GMT</pubDate>
            <atom:updated>2026-03-27T20:07:57.023Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, everybody. I’ve recently embarked on an autodidactic journey into the world of FPGA design. No course. No structured curriculum. Just curiosity. This 66-Day series is where I document what I learn — step by step, mistake by mistake. Let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*cv7ISrN12RjZ0S2jpiVAhg.gif" /></figure><p>Today, I built my first circuit on the TANG Nano 9K, and the first thing I noticed — as a software engineer — was the difference between <strong>coding a sequence of instructions</strong> and <strong>architecting a physical hardware circuit</strong>.</p><p>This means that in hardware, everything happens simultaneously. There is no waiting for the previous line to finish. If you have ten different processes, they all breathe and react at the exact same moment, driven by the system’s “heartbeat” — the <strong>Clock signal</strong>. Let’s me explain this through a small practical example.</p><h3>Step 1: Defining the Hardware with Verilog</h3><p>In software engineering, when you open a .cpp file, you are writing a set of instructions for a processor to execute. But in the world of FPGA, when you open a .v (Verilog) file, you are <strong>describing the physical structure of a circuit.</strong></p><pre>module top(<br>    input wire button1,<br>    input wire button2,<br>    output wire [1:0] leds<br>);<br><br>assign leds[0] = button1;<br>assign leds[1] = button2;<br><br>endmodule</pre><ul><li><strong>module top(...)</strong>: This is the name of our primary schematic. Think of it like a main function in software, but instead of a routine, it represents a physical &quot;box.&quot;</li><li><strong>input wire and </strong><strong>output wire</strong>: The keyword wire is crucial here. These variables do not store data; they represent actual conductors that carry electrical signals from one point to another.</li><li><strong>assign leds[0] = button1;</strong>: In software, this looks like an assignment. In hardware, this is a <strong>&quot;soldering&quot;</strong> operation. It tells the FPGA to permanently connect the signal from button1 to leds[0]. While a software line executes and moves on, this hardware connection remains <strong>active and instantaneous</strong> as long as the power is on.</li></ul><blockquote>This isn’t an instruction — it’s an <strong>interconnect</strong>. I’ve just wired two physical pins together using nothing but a line of Verilog.</blockquote><h3>Step 2: Synthesis — Transforming Code into Logic Gates</h3><p>In the software world, compiling code results in a set of instructions for the CPU to execute. In the FPGA world, <strong>Synthesis</strong> is the magical bridge where your high-level description becomes a <strong>Gate-Level Netlist</strong>.</p><h4>What Happens During Synthesis?</h4><ul><li><strong>Translation:</strong> The synthesizer (Gowin EDA) analyzes your Verilog and determines how to build that specific logic using the FPGA’s internal resources, such as <strong>Look-Up Tables (LUTs)</strong>, <strong>Flip-Flops</strong>, and <strong>Logic Gates</strong>.</li><li><strong>Creating the Netlist:</strong> Once synthesis is complete, the “code” ceases to exist as a sequence of text. Instead, it becomes a <strong>Netlist</strong> — a massive, complex blueprint describing every single physical interconnection required to realize your design.</li><li><strong>Optimization:</strong> The synthesizer acts like a master electrical engineer, optimizing the circuit to use the fewest resources or achieve the fastest possible signal timing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*t2sY15WDeM0kygwSnEEQZA.png" /><figcaption>Synthesize Verilog File</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YA6-wd9TwQVMxuKmqF0JaA.png" /><figcaption>RTL Design Viewer (Go to Tools&gt;Schematic Viewer&gt;RTL Design Viewer)</figcaption></figure><blockquote>In software, a compiler translates logic into time (clock cycles); in FPGA, a synthesizer translates logic into space (silicon area).</blockquote><h3>Step 3: CST Files and Pin Mapping</h3><p>After synthesis, we have a perfect logic schematic, but its inputs and outputs are still “floating” in a virtual space. We need to tell the FPGA which signal goes to which physical leg (pin) on the chip.</p><h4>The .cst (Constraint) File: The Address Book</h4><p>The Constraint file is where you map your Verilog signal names to physical hardware addresses. For example, you define that the signal named button1 in your code is actually <strong>Pin 4</strong> on the board.</p><h4>Why Pin 10? Why Pin 4?</h4><p>These numbers are not arbitrary. The manufacturer of the Tang Nano 9K has physically soldered the LEDs and buttons to these specific pins during production. If you map leds[0] to Pin 50 instead of Pin 10, the FPGA will send electricity to Pin 50, but since nothing is connected there, you won&#39;t see any light.</p><h4>IO_TYPE and Voltage Levels</h4><p>Mapping the pin is only half the battle. You must also define the <strong>IO_TYPE</strong> (e.g., LVCMOS18 for 1.8V). Choosing the correct voltage level ensures that the FPGA talks to the onboard components in a language (and voltage) they understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9_rPSrFlsp8EO6pm_R5ig.png" /><figcaption>Floor Planner</figcaption></figure><blockquote>In software, a variable is an address in RAM. In FPGA, a variable is a physical piece of copper on the chip.</blockquote><h3>Step 4: Place &amp; Route and The Final Program</h3><p>Now that we have the schematic (Netlist) and the physical addresses (CST), it’s time for the final “deployment.”</p><h4>Place &amp; Route: Solving the Silicon Maze</h4><p>This is where the software decides exactly which logic cells inside the FPGA to use (<strong>Place</strong>) and how to connect them using the internal routing tracks (<strong>Route</strong>). Think of it as solving a massive 3D puzzle to find the shortest, fastest electrical path for your signals.</p><h4>The Bitstream (.fs File)</h4><p>The output of this process is a <strong>Bitstream</strong>. This isn’t a program in the traditional sense; it is a high-density binary map that tells the FPGA exactly which of its millions of internal switches should be “On” or “Off” to form your circuit.</p><p>The final step is sending this map to the board via USB.</p><ul><li><strong>SRAM Mode:</strong> Perfect for quick testing; the design disappears when power is lost.</li><li><strong>Embedded Flash:</strong> The permanent choice; your circuit “wakes up” every time the board is powered on.</li></ul><p>The final step is sending this map to the board via USB.</p><ul><li><strong>SRAM Mode:</strong> Perfect for quick testing; the design disappears when power is lost.</li><li><strong>Embedded Flash:</strong> The permanent choice; your circuit “wakes up” every time the board is powered on.</li></ul><p>And it is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*CaRNmnNddodU_Jfg8lHrLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZUHEkVJ7B41lM1SA5plxw.png" /></figure><p>I moved from ‘Hello World’ to ‘Hello Hardware’. This is just the beginning of my FPGA journey. Stay tuned for more!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*-EfoYO52Lbzpl27GgkkGGw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6043fea949ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming Essentials- Notes to Self]]></title>
            <link>https://medium.com/@rumeysalayik/object-oriented-programming-essentials-notes-to-self-786b512bce4a?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/786b512bce4a</guid>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 16:03:55 GMT</pubDate>
            <atom:updated>2024-12-30T19:12:17.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UFi9cCYYmMQ_owhQaecJQ.png" /></figure><p><strong>What is class?</strong></p><p>A class is a blueprint that defines the properties (attributes) and behaviors (methods) of an object.</p><p><strong>What is object?</strong></p><p>An object is an instance of a class, and it can access the properties and behaviors defined in its class.</p><p><strong>What is abstraction?Give the code exaple.</strong></p><p>Abstraction is to hide the complex implementation details of a system and exposing only the necessary and relevant aspects to the user. We cannot create an object from an abstract class.</p><blockquote>Abstract class is a class that has <strong>at least one</strong> pure virtual function.</blockquote><p>For example;</p><p><em>Shape</em> is an abstract class with <strong>a pure virtual function</strong> calculateArea(). The function has no implementation in the Shape class and <strong>must </strong>be implemented by derived classes.</p><pre>#ifndef SHAPE_H<br>#define SHAPE_H<br><br><br>class Shape<br>{<br><br>public:<br>    Shape();<br>    virtual unsigned int calculateArea()=0;<br>    virtual ~Shape() {}<br>    unsigned int m_area;<br>};<br><br>#endif // SHAPE_H</pre><pre>#include &quot;shape.h&quot;<br><br>Shape::Shape()<br>{<br>}</pre><pre>#ifndef CIRCLE_H<br>#define CIRCLE_H<br><br>#include &quot;shape.h&quot;<br>#define MATH_PI 3<br><br>class Circle : public Shape<br>{<br>public:<br>    Circle( unsigned int a_radius );<br><br>    // Shape interface<br>public:<br>    unsigned int calculateArea() override;<br>private:<br>    unsigned int m_radius;<br>};<br><br>#endif // CIRCLE_H</pre><pre>#include &quot;circle.h&quot;<br><br>Circle::Circle( unsigned int a_radius )<br>{<br>    m_radius = a_radius;<br>}<br><br><br>unsigned int Circle::calculateArea()<br>{<br>    m_area = MATH_PI*m_radius*m_radius;<br>    return m_area;<br>}</pre><pre>#ifndef RECTANGE_H<br>#define RECTANGE_H<br><br>#include &quot;shape.h&quot;<br><br>class Rectange : public Shape<br>{<br>public:<br>    Rectange( unsigned int a_width, unsigned int a_height );<br>private:<br>    unsigned int m_width;<br>    unsigned int m_height;<br><br>    // Shape interface<br>public:<br>    unsigned int calculateArea() override;<br>};<br><br>#endif // RECTANGE_H</pre><pre>#include &quot;rectange.h&quot;<br><br>Rectange::Rectange( unsigned int a_width, unsigned int a_height )<br>{<br>    m_width = a_width;<br>    m_height = a_height;<br>}<br><br><br>unsigned int Rectange::calculateArea()<br>{<br>    m_area = m_width*m_height;<br>    return m_area;<br>}</pre><pre>#include &lt;QCoreApplication&gt;<br>#include &quot;circle.h&quot;<br>#include &quot;rectange.h&quot;<br>#include &lt;QDebug&gt;<br><br>int main(int argc, char *argv[])<br>{<br>    QCoreApplication a(argc, argv);<br><br>    Shape* circle = new Circle( 5 );<br>    Shape* rectangle = new Rectange( 2, 5 );<br><br>    qDebug() &lt;&lt; &quot;Circle Area: &quot; &lt;&lt; circle-&gt;calculateArea();<br>    qDebug() &lt;&lt; &quot;Rectangle Area:&quot; &lt;&lt; rectangle-&gt;calculateArea();<br><br>    delete circle;<br>    delete rectangle;<br><br>    return a.exec();<br>}</pre><p>We create pointers to the abstract class Shape, but instantiate concrete classes (Circle and Rectangle). Even though we don&#39;t know the actual implementation of draw(), we can still call it, thanks to abstraction.</p><p><strong>What is interface?</strong></p><p>As I mentioned above if a class contains at least one class we say it is an abstract class. And if all functions of a class are pure virtual function it is an interface.</p><p>The purpose of an interface is to specify which functions a class should have. Data members (properties), on the other hand, are typically used to store the state of a class, and this is not the role of interfaces. If data members are added to an interface, it ceases to be an interface and becomes a regular class instead.</p><p><strong>What is inheritance?</strong></p><p><strong>Inheritance</strong> allows a class (the derived or child class) to inherit properties (data members and methods) from another class (the base or parent class).</p><ul><li>enhance code reusability</li><li>makes it easier to manage more complex systems</li></ul><p><strong>Types of Inheritance:</strong></p><ul><li><strong>Single Inheritance</strong>: A derived class inherits from a single base class.</li><li><strong>Multiple Inheritance</strong>: A derived class inherits from multiple base classes. This is supported in languages like C++, but some languages (e.g., Java) only support single inheritance.</li><li><strong>Hierarchical Inheritance</strong>: A single base class is inherited by multiple derived classes.</li><li><strong>Multilevel Inheritance</strong>: A derived class inherits from another derived class.</li></ul><p>In normal, multiple inheritance causes a problem that is called as<strong><em> Diamond Problem. </em></strong>Let’s look at how C++ handle this problem. Diamond problem occurs when two classes inherit from the same base class and a third class inherits from both of these classes. If the base class has a method that is overridden in both derived classes, it’s unclear which method the third class should inherit.</p><pre>    A<br>   / \<br>  B   C<br>   \ /<br>    D</pre><pre>#include &lt;iostream&gt;<br><br>class A {<br>public:<br>    void foo() {<br>        std::cout &lt;&lt; &quot;A&#39;s foo&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class B : public A {<br>public:<br>    void foo() {<br>        std::cout &lt;&lt; &quot;B&#39;s foo&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class C : public A {<br>public:<br>    void foo() {<br>        std::cout &lt;&lt; &quot;C&#39;s foo&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class D : public B, public C {<br>};</pre><p>The critical question is that which class’ foo function will be call if I call foo() function of D object? Class B or Class C? It is ambiguous. This is diamond problem.</p><pre>D obj;<br>obj.foo();  //which foo function?</pre><p>First solution is to specify exactly with the scope resolution operator(::).</p><pre>D obj;<br>obj.B::foo();  // B&#39;s foo method is called<br>obj.C::foo();  // C&#39;s foo method is called</pre><p>Second solution is to use virtual inheritance. As shown below, class B and class C are inherited from class A as virtual. In regular inheritance, the derived class may end up with multiple copies of the base class, leading to ambiguity (diamond problem). In virtual inheritance, only a single copy of the base class is created, resolving the diamond problem.</p><pre>#include &lt;iostream&gt;<br><br>class A {<br>public:<br>    void show() {<br>        std::cout &lt;&lt; &quot;A&#39;s show&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class B : virtual public A {};<br>class C : virtual public A {};<br><br>class D : public B, public C {};<br><br>int main() {<br>    D obj;<br>    obj.show();  // Works fine, calls A&#39;s show() method<br>}</pre><p>What is polymorphism?</p><p>‘Polymorphism’ means ‘having many forms’.Polymorphism allows you to define one interface and have multiple implementations. There are 2 types of polymorphism.</p><ul><li><strong>Compile-time Polymorphism</strong></li></ul><p>It occurs via either a function or an operator is overloaded.</p><p><strong>Function Overloading</strong></p><p>Sometimes we need to functions that they have the same functionality but with different parameter types. For example, a user can want to add 2 integer numbers or 2 double numbers in calculator. In that case, we define functions with <strong>the same name </strong>and different parameter types.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Math {<br>public:<br>    // Function to add two integers<br>    int add(int a, int b) {<br>        return a + b;<br>    }<br><br>    // Function to add two doubles<br>    double add(double a, double b) {<br>        return a + b;<br>    }<br><br>    // Function to add three integers<br>    int add(int a, int b, int c) {<br>        return a + b + c;<br>    }<br>};<br><br>int main() {<br>    Math math;<br>    cout &lt;&lt; &quot;Sum of 2 and 3: &quot; &lt;&lt; math.add(2, 3) &lt;&lt; endl;            // Calls the first function<br>    cout &lt;&lt; &quot;Sum of 2.5 and 3.5: &quot; &lt;&lt; math.add(2.5, 3.5) &lt;&lt; endl;  // Calls the second function<br>    cout &lt;&lt; &quot;Sum of 1, 2 and 3: &quot; &lt;&lt; math.add(1, 2, 3) &lt;&lt; endl;    // Calls the third function<br><br>    return 0;<br>}</pre><p><strong>Operator Overloading</strong></p><p>It allows you to redefine the behavior of operators (such as +, -, *, /, etc.) for user-defined types. We assign custom behaviour to operators.</p><pre>#include &lt;iostream&gt;<br><br>class Point {<br>private:<br>    int x, y; // Koordinatlar<br><br>public:<br>    // Constructor<br>    Point(int x, int y) : x(x), y(y) {}<br><br>    // Overloading the + operator as a member function<br>    Point operator+(const Point&amp; other) {<br>        return Point(x + other.x, y + other.y); // Özel üyelere doğrudan erişim<br>    }<br><br>    // Metod: Noktanın koordinatlarını yazdırmak için<br>    void print() const {<br>        std::cout &lt;&lt; &quot;(&quot; &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y &lt;&lt; &quot;)&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>int main() {<br>    Point p1(1, 2); // Birinci nokta (1, 2)<br>    Point p2(3, 4); // İkinci nokta (3, 4)<br><br>    Point p3 = p1 + p2; // p1 ve p2 noktalarının toplamı<br><br>    std::cout &lt;&lt; &quot;Point 1: &quot;;<br>    p1.print(); // (1, 2) yazdır<br>    std::cout &lt;&lt; &quot;Point 2: &quot;;<br>    p2.print(); // (3, 4) yazdır<br>    std::cout &lt;&lt; &quot;Point 3 (Point 1 + Point 2): &quot;;<br>    p3.print(); // (4, 6) yazdır<br><br>    return 0;<br>}</pre><blockquote>NOTE: Some operators (like ::, . , .*, and ?:) cannot be overloaded.</blockquote><p><strong>Run-time Polymorphism</strong></p><p>It is achieved using <strong>virtual functions</strong> and <strong>inheritance. </strong>It is called <strong>function overloading</strong>.</p><p><strong>What is overloading?</strong></p><p>We have a method in parent class and we redefine(with <strong>override</strong> keyword) that method with the same signature in the subclass according to its own needs and requirements. The method to call is determined at runtime based on the object type.</p><pre>class Animal {<br>public:<br>    virtual void sound() {<br>        std::cout &lt;&lt; &quot;Animal sound&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class Dog : public Animal {<br>public:<br>    void sound() override { // Overriding the sound method<br>        std::cout &lt;&lt; &quot;Bark&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>int main() {<br>    Animal* myDog = new Dog();<br>    myDog-&gt;sound(); // Output: Bark<br>    delete myDog;<br>    return 0;<br>}</pre><p>Even though a subclass object is accessed with a reference of the superclass type, the overridden method of the subclass is called. The aim of polymorphism is changing the functionality of a function which is inherited from a parent class.</p><p><strong>Pay attention!!!!!!!!!!</strong></p><p>Look at the code below. Is this an polymorphism example?</p><pre>#include &lt;QCoreApplication&gt;<br>#include &lt;iostream&gt;<br><br>class Animal {<br>public:<br>    void sound() {<br>        std::cout &lt;&lt; &quot;Animal sound&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class Dog : public Animal {<br>public:<br>    void sound() { // Overriding the sound method<br>        std::cout &lt;&lt; &quot;Bark&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>int main(int argc, char *argv[])<br>{<br>    QCoreApplication a(argc, argv);<br>    Animal* myDog = new Dog();<br>    myDog-&gt;sound(); // Output: Animal sound<br>    delete myDog;<br>    return a.exec();<br>}</pre><p>Nope. Even though redefining the <em>sound()</em> function it is just inheritance example. Polymorphism is obtained via virtual functions.</p><p>In short, when a <strong>virtual function</strong> is used, the function called is determined by the <strong>actual type of the object</strong> that the pointer points to, not by the type of the pointer itself. This is known as <strong>dynamic binding</strong> or <strong>runtime polymorphism</strong>.</p><p>For <strong>non-virtual functions</strong>, the function call is determined by the <strong>type of the pointer</strong> itself, regardless of the actual object it points to. This is called <strong>static binding</strong> or <strong>compile-time binding</strong>.</p><p><strong>What is encapsulation?</strong></p><p>Encapsulation allows data and functions to be bundled within an object, limiting direct access to the data from outside the object and allowing controlled access.</p><p>Key Purposes of Encapsulation</p><ul><li><strong>Data Privacy and Security</strong>: Restricts direct access to the internal data of an object, ensuring data security.</li><li><strong>Data Integrity and Consistency</strong>: Access and updates to the data are managed through the methods provided by the class, preventing invalid or inconsistent data from being entered externally.</li><li><strong>Ease of Maintenance and Flexibility</strong>: The inner workings of the object are hidden from outside code, so changes to the object’s behavior do not affect the code that relies on it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=786b512bce4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID PRENSİPLERİ-2]]></title>
            <link>https://medium.com/@rumeysalayik/solid-prensi%CC%87pleri%CC%87-2-79032bbc9b84?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/79032bbc9b84</guid>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 10:57:22 GMT</pubDate>
            <atom:updated>2024-01-27T10:57:22.284Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Liskov’un Yerine Geçme Prensibi</strong></h3><p>Merhaba, SOLID prensiplerinden bahsettiğim bu seride 2. olarak Liskov’un Yerine Geçme Prensibi(Liskov Substitution Principle) ile devam ediyoruz. Bu prensibe göre bir sınıfta bulunan herhangi bir işlev, kendisinden kalıtım alan sınıflarda da kullanılmalıdır. Bir örnekle detaylandıralım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*w3irY1z1rTfVXv5WNDYoqQ.jpeg" /></figure><p>Örneğin <em>IAnimal</em> adında bir arayüz(interface) ve bu arayüzden kalıtım almış Owl ve <em>Chicken</em> sınıflarımız olsun. <em>IAnimal</em> arayüzünde <em>Walk</em> ve <em>Fly</em> adında iki fonksiyonumuz yer alıyor. Baykuş ve tavuklar hem uçma hem de yürüme yeteneğine sahiptir. Bu yüzden <em>IAnimal</em> arayüzünde <strong><em>virtual</em></strong> olarak tanımlanmış <em>Walk</em> ve <em>Fly </em>fonksiyonlarını override anahtar kelimesi ile tekrar kendilerine göre yazarak kullanabilirler.</p><blockquote>Owl <em>ve</em> Chicken <em>sınıfları </em>IAnimal<em> arayüzünde</em> virtual <em>olarak tanımlanmış</em> Walk <em>ve</em> Fly<em> fonksiyonlarını </em><strong>override</strong><em> anahtar kelimesi ile tekrar kendilerine göre yazarak kullanabilirler.</em></blockquote><pre>#include &lt;iostream&gt;<br><br>using namespace std;<br><br><br>class IAnimal<br>{<br>public:<br>    virtual void  Fly() {} <br>    virtual void Walk() {} <br>};<br><br>class Owl: public IAnimal<br>{<br>    public:<br>        Owl()<br>        {<br>            cout &lt;&lt; &quot;Owl is created.&quot; &lt;&lt; endl;<br>        }<br>        void Fly() override<br>        {<br>            cout &lt;&lt; &quot;Owl can fly.&quot; &lt;&lt; endl;<br>        }<br>        void Walk() override<br>        {<br>            cout &lt;&lt; &quot;Owl can walk.&quot; &lt;&lt; endl;<br>        } <br>};<br><br>class Chicken: public IAnimal<br>{<br>    public:<br>        Chicken()<br>        {<br>            cout &lt;&lt; &quot;Chicken object is created.&quot; &lt;&lt; endl;<br>        }<br>        void Fly() override<br>        {<br>            cout &lt;&lt; &quot;Chicken can fly.&quot; &lt;&lt; endl;<br>        }<br>        void Walk() override<br>        {<br>            cout &lt;&lt; &quot;Chicken can walk.&quot; &lt;&lt; endl;<br>        }<br>};<br><br>int main()<br>{<br><br>    Owl owl;<br>    Chicken chicken;<br><br>    owl.Walk();<br>    owl.Fly();<br><br>    chicken.Walk();<br>    chicken.Fly();<br><br>    return 0;<br>}</pre><p>Yukarıdaki kodun çıktısı tahmin edildiği üzere aşağıdaki gibi olacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pdrK1THOAtigDSCM1fr5g.png" /></figure><p>Ancak ben bu koda <em>Cat</em> sınıfını eklemek istersem nasıl olacak? Kedi de bir hayvan o yüzden <em>IAnimal</em> sınıfından kalıtım almalıdır. Ancak kedilerin yürüme yeteneği varken uçma yetenekleri yoktur. <em>IAnimal</em><strong> sınıfından türetmeme rağmen Fly fonksiyonunu override etmem hiç mantıklı değil.</strong> Yazının başında belirttiğim gibi Liskov’un yerine geçme prensibine göre bir sınıfta bulunan herhangi bir işlev, kendisinden kalıtım alan sınıflarda da kullanılmalıdır.Eğer <em>Cat</em> sınıfını <em>IAnimal</em> sınıfından türetir ama <em>Fly</em> fonksiyonunu override etmezsem bu prensibe uymamış olacağız. Peki bu kodu Liskov Substitution Principle’e uygun şekilde nasıl yazabiliriz?</p><p>Burada işlevleri ayırmak en doğru yöntem olacaktır. <em>IFly</em> ve <em>IWalk</em> adında iki arayüz tanımlıyorum. Böylece yeni bir sınıf oluşturulmak istendiğinde sınıfın sadece gerekli işlevi barındıran arayüzden kalıtım alması yeterli olacaktır.</p><pre>#include &lt;iostream&gt;<br><br>using namespace std;<br><br>class IFly{<br>    public:<br>        virtual void  Fly() {} <br>};<br><br>class IWalk<br>{<br>    public:<br>        virtual void Walk() {} <br>};<br><br>class Owl: public IFly, public IWalk<br>{<br>    public:<br>        Owl()<br>        {<br>            cout &lt;&lt; &quot;Owl is created.&quot; &lt;&lt; endl;<br>        }<br>        void Fly() override<br>        {<br>            cout &lt;&lt; &quot;Owl can fly.&quot; &lt;&lt; endl;<br>        }<br>        void Walk() override<br>        {<br>            cout &lt;&lt; &quot;Owl can walk.&quot; &lt;&lt; endl;<br>        } <br>};<br><br>class Chicken: public IFly, public IWalk<br>{<br>    public:<br>        Chicken()<br>        {<br>            cout &lt;&lt; &quot;Chicken object is created.&quot; &lt;&lt; endl;<br>        }<br>        void Fly() override<br>        {<br>            cout &lt;&lt; &quot;Chicken can fly.&quot; &lt;&lt; endl;<br>        }<br>        void Walk() override<br>        {<br>            cout &lt;&lt; &quot;Chicken can walk.&quot; &lt;&lt; endl;<br>        }<br>};<br><br>class Cat: public IWalk<br>{<br>    public:<br>        Cat()<br>        {<br>            cout &lt;&lt; &quot;Cat object is created.&quot; &lt;&lt; endl;<br>        }<br>        void Walk() override<br>        {<br>            cout &lt;&lt; &quot;Cat can walk.&quot; &lt;&lt; endl;<br>        }<br>};<br><br>int main()<br>{<br>    Owl owl;<br>    Chicken chicken;<br>    Cat cat;<br><br>    owl.Walk();<br>    owl.Fly();<br><br>    chicken.Walk();<br>    chicken.Fly();<br><br>    cat.Walk();<br><br>    return 0;<br>}</pre><p><em>Chicken</em> ve <em>Owl</em> sınıfları her iki yeteneğe de sahip olduğu için <em>IFly</em> ve <em>IWalk </em>arayüzlerinden kalıtım aldı. <em>Cat</em> sınıfı ise sadece <em>IWalk</em> sınıfından kalıtım almış oldu.Böylece bir sınıfın kullanmayacağı işlevi override etmemiş olduk. Umarım faydalı olmuştur.Bir sonraki yazıda görüşmek üzere…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79032bbc9b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID PRENSİPLERİ-1]]></title>
            <link>https://medium.com/@rumeysalayik/solid-prensi%CC%87pleri%CC%87-96ab4801ac9b?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ab4801ac9b</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 13:46:18 GMT</pubDate>
            <atom:updated>2024-01-27T10:59:25.673Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese merhaba, bugün sizlere geliştirdiğimiz yazılımın daha okunabilir, esnek ve tekrar kullanılabilir olmasını sağlamak için dikkat etmemiz gereken S<strong>O</strong>LID prensiplerinden biri olan Açık/Kapalılık (Open/Closed Principle) prensibinden bahsedeceğim. Haydi başlayalım…</p><p><strong>Açık/Kapalılık Prensibi</strong>(Open/Closed Principle)</p><p>Bir sınıf veya fonksiyon gibi yazılım birimleri genişletilebilir ancak değiştirilemez olmalıdır. Yani yazılımımıza yeni bir özellik eklerken mevcut sınıfı veya fonksiyonu değiştirmek yerine, yeni kod ekleyerek genişletme yapabilmeliyiz. Bir örnek üzerinden anlamaya çalışalım.</p><p><em>Shape</em> ve <em>AreaCalculator</em> adında iki tane sınıfımız var. AreaCalculator sınıfının <em>calculateArea</em> fonksiyonuna argüman olarak verilen <em>Shape</em> sınıfı objesinin alanını hesaplamaktadır. Bu örnekte <em>Shape</em> sınıfının ve <em>AreaCalculator</em> sınıfının açık/kapalılık prensibine uygun olup olmadığını değerlendirelim.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>using namespace std;<br><br>#define PI 3.14<br><br>class Shape {<br>private:<br>    string type;<br><br>public:<br>    Shape(const string&amp; type) : type(type) {}<br><br>    string getType() const {<br>        return type;<br>    }<br>};<br><br>class AreaCalculator {<br>public:<br>    double calculateArea(const Shape&amp; shape, int a_unit) const {<br>        if (shape.getType() == &quot;Circle&quot;) {<br>            // Calculate area for a circle<br>            return PI * a_unit * a_unit;<br>        }<br><br>        return 0;<br>    }<br>};<br><br>int main() {<br>    Shape circle(&quot;Circle&quot;);<br><br>    AreaCalculator areaCalculator;<br><br>    // Calculate and print areas<br>    cout &lt;&lt; &quot;Circle Area: &quot; &lt;&lt; areaCalculator.calculateArea(circle, 5) &lt;&lt; endl;<br><br>    return 0;<br>}</pre><p>Şöyle bir soru soruyorum kendime, örneğin main fonksiyonu içerisinde yeni bir şeklin, örneğin kare, alanını hesaplamak istersem ne yapmam gerekiyor?</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>using namespace std;<br><br>#define PI 3.14<br><br>class Shape {<br>private:<br>    string type;<br><br>public:<br>    Shape(const string&amp; type) : type(type) {}<br><br>    string getType() const {<br>        return type;<br>    }<br>};<br><br><br>class AreaCalculator {<br>public:<br>    double calculateArea(const Shape&amp; shape, int a_unit) const {<br>        if (shape.getType() == &quot;Circle&quot;) {<br>            // Calculate area for a circle<br>            return PI * a_unit * a_unit;<br>        } else if (shape.getType() == &quot;Square&quot;) {<br>            // Calculate area for a square<br>            return a_unit * a_unit;<br>        }<br><br>        return 0;<br>    }<br>};<br><br>int main() {<br>    Shape circle(&quot;Circle&quot;);<br>    Shape square(&quot;Square&quot;);<br><br>    AreaCalculator areaCalculator;<br><br>    // Calculate and print areas<br>    cout &lt;&lt; &quot;Circle Area: &quot; &lt;&lt; areaCalculator.calculateArea(circle, 5) &lt;&lt; endl;<br>    cout &lt;&lt; &quot;Square Area: &quot; &lt;&lt; areaCalculator.calculateArea(square, 3) &lt;&lt; endl;<br><br>    return 0;<br>}<br> </pre><p><em>AreaCalculator</em> sınıfı içerisindeki <em>calculateArea</em> fonksiyonunu güncellememiz gerekecek. Bu durum açıklık kapalılık prensibine uymamaktadır. Çünkü ilk kodda fonksiyon sadece dairenin alanını hesaplayabilmekteydi ve <em>Shape</em> sınıfından oluşturulmuş olan başka bir şeklin alanını hesaplamaya kapalı bir fonksiyon. Şimdi kodu açık/kapalılık prensibine göre uygun hale getirerek oluşabilecek yeni bir şeklin hesaplanması ihtimallerine karşı açık hale getirelim.</p><p>Genel resme baktığımızda fark etmemiz gereken şeyler şunlar;</p><ol><li><em>circle</em> ve <em>square</em> objeleri Shape sınıfından yaratılıyorlar ve ikisi de <em>calculateArea </em>fonksiyonuna ihtiyaç duyuyorlar.</li></ol><ul><li>Bu da demek oluyor ki ortaklanabilir özelliklere sahipler ve ortak olan özelliklerini bir sınıfta tutup kendilerine özgü olan özelliklerini de bu sınıftan kalıtım alan alt sınıflarda tutabiliriz.<br>- <em>Shape</em> adında soyut sınıf oluşturalım ve bu sınıftan kalıtım alan <em>Square</em> ve <em>Circle</em> adında iki alt sınıf oluşturalım.</li></ul><blockquote>Alt sınıfların, ortak bir soyut sınıftan veya arayüzden türemesini sağlayarak kodun genişletilebilirliğini sağlamış oluruz.</blockquote><p>2. Her iki obje de <em>calculateArea </em>fonksiyonunu kullansa da hesaplama formülleri yani fonksiyonun içeriği birbirinden farklı.</p><ul><li>Bu durumda polymorphism(çok biçimlilik) yapısını kullanmalıyız. Böylece ister <em>circle</em> ister <em>square</em> ister başka bir Shape sınıfından oluşturulmuş bir obje olsun aynı isimdeki( fonksiyon ismi aynı ancak fonksiyonun içi farklı) <em>calculateArea</em> fonksiyonu üzerinden alan hesabını yapacaktır.</li></ul><blockquote>Her alt sınıf, kendi özel davranışlarını uygulayarak genel davranışları genişletebilir.</blockquote><p>Kodun yeni hali aşağıda görülmektedir.</p><pre>#include &lt;iostream&gt;<br><br>using namespace std;<br><br>class Shape {<br>public:<br>    /*<br>    * area fonksiyonu &quot;pure virtual function&quot; olduğu için Shape sınıfından<br>    * kalıtım alan tüm alt sınıflar bu fonksiyonu kendine göre implemente etmek<br>    * zorundadır!<br>    */<br>    virtual float area() const = 0;<br>};<br><br>class Square : public Shape {<br>public:<br>    float edge;<br>    <br>    Square(float e) : edge(e) {}<br><br>    float area() const override {<br>        return edge * edge;<br>    }<br>};<br><br>class Circle : public Shape {<br>public:<br>    float radius;<br>    <br>    Circle(float r) : radius(r) {}<br><br>    float area() const override {<br>        return 3.14f * radius * radius;<br>    }<br>};<br><br>class AreaCalculator {<br>public:<br>    float calculateArea(const Shape&amp; shape) {<br>        return shape.area();<br>    }<br>};<br><br>int main() {<br>    Square square(2);<br>    Circle circle(5);<br>    AreaCalculator calculator;<br><br>    cout &lt;&lt; &quot;Square Area: &quot; &lt;&lt; calculator.calculateArea(square) &lt;&lt; endl;<br>    cout &lt;&lt; &quot;Circle Area: &quot; &lt;&lt; calculator.calculateArea(circle) &lt;&lt; endl;<br><br>    return 0;<br>}</pre><p>Yukarıdaki resimde görüldüğü gibi tüm şekiller <em>AreaCalculator</em> sınıfının <em>calculateArea</em> fonksiyonu üzerinden kendi alan hesabını yapabilmektedir.</p><p>Şimdi yazdığımız kodun bu prensibe uyup uymadığına tekrar bakalım. Örneğin bir dikdörtgenin alanını hesaplamak istersek, <em>Shape</em> sınıfından kalıtım alan <em>Rectangle</em> adında bir sınıf oluşturup ve <em>area</em> fonksiyonunu kendine uygun olarak yazmamız yeterli olacaktır.</p><pre>#include &lt;iostream&gt;<br><br>using namespace std;<br><br>class Shape {<br>public:<br>    /*<br>    * area fonksiyonu &quot;pure virtual function&quot; olduğu için Shape sınıfından<br>    * kalıtım alan tüm alt sınıflar bu fonksiyonu kendine göre implemente etmek<br>    * zorundadır!<br>    */<br>    virtual float area() const = 0;<br>};<br><br>class Square : public Shape {<br>public:<br>    float edge;<br>    <br>    Square(float e) : edge(e) {}<br><br>    float area() const override {<br>        return edge * edge;<br>    }<br>};<br><br>class Circle : public Shape {<br>public:<br>    float radius;<br>    <br>    Circle(float r) : radius(r) {}<br><br>    float area() const override {<br>        return 3.14f * radius * radius;<br>    }<br>};<br><br>class Rectangle : public Shape {<br>public:<br>    float width, height;<br>    <br>    Rectangle(float w, float h) : width(w), height(h) {}<br><br>    float area() const override {<br>        return width * height;<br>    }<br>};<br><br>class AreaCalculator {<br>public:<br>    float calculateArea(const Shape&amp; shape) {<br>        return shape.area();<br>    }<br>};<br><br>int main() {<br>    Square square(2);<br>    Circle circle(5);<br>    Rectangle rectangle(2, 10);<br>    AreaCalculator calculator;<br><br>    cout &lt;&lt; &quot;Square Area: &quot; &lt;&lt; calculator.calculateArea(square) &lt;&lt; endl;<br>    cout &lt;&lt; &quot;Circle Area: &quot; &lt;&lt; calculator.calculateArea(circle) &lt;&lt; endl;<br>    cout &lt;&lt; &quot;Rectangle Area: &quot; &lt;&lt; calculator.calculateArea(rectangle) &lt;&lt; endl;<br>    return 0;<br>}</pre><p>Görüldüğü gibi <em>Shape, Circle, Square </em>veya<em> AreaCalculator </em>sınıflarını güncellememize gerek olmadan sadece ihtiyacımıza göre <em>Rectangle</em> sınıfı oluşturarak yeni bir özellik ekledik. Açık/Kapalılık prensibi ile yazdığımız kodun tekrar kullanılabilirliğini ve sürdürülebilirliğini sağlamış oluyoruz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ab4801ac9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegates and Events]]></title>
            <link>https://medium.com/@rumeysalayik/what-is-delegates-2b49edf04db8?source=rss-ff9787923c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b49edf04db8</guid>
            <category><![CDATA[event-example]]></category>
            <category><![CDATA[delegate-vs-event]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[types-of-delegate]]></category>
            <category><![CDATA[delegate]]></category>
            <dc:creator><![CDATA[Rumeysa Layık]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 22:04:20 GMT</pubDate>
            <atom:updated>2023-02-05T11:39:17.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*Giwkqn_ZsRU7p8Jwvf-kog.png" /></figure><p>Hi, everybody. Today, basically, I am going to mention about delegates and events which are quite essential topics for asynchronous programming. I will give answer the following questions and give the examples.</p><ul><li>What are delegates and events?</li><li>Why we need delegates and events?</li><li>How to create and use them?</li><li>What kinds of delegates are there?</li><li>What are the differences between a delegates and an event?</li></ul><p>A delegate is a variable which <strong>holds a method</strong> instead of data. To understand clearly, firstly, I will show the similarity with a class which can hold a group of variables and related methods.</p><p>For example: Let’s create <em>Student </em>class which hold a student’s Id, name and age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*ddMTrbUvQcjXCx7sFjOUBQ.png" /></figure><p>And I will create two objects named <em>student1 </em>and <em>student2.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*A9SFx5tLFg9gAowskJUbbw.png" /></figure><p>As we know, <em>student1 </em>is like a reference to access Rumeysa’s information (Id, Name, Age) in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*YtbisVbgI-8YY6q33s7u1A.png" /></figure><p>Like classes, a delegate is a reference which <strong>holds a method. </strong>Let’s define a delegate. Firstly, we create the signature of the delegate with <strong>delegate </strong>keyword. The name of my delegate is <strong><em>Operate. </em></strong>With that line I said, my delegate can only hold methods which take 2 integer parameters and return an integer value. Think it as class definition.</p><pre>public delegate int Operate( int a, int b );</pre><p>And let’s create delegate object named <strong><em>AritmeticOperation</em></strong> and also a function named <strong><em>Sum </em></strong>which has the same signature with our delegate. We assign <strong><em>Sum</em></strong> function to <strong><em>AritmeticOperation</em></strong> to delegate it and call the delegate. When we call delegate, it give the parameters to the function which is delegated and run it. We can alternatively use Invoke method too. I also did null check (?) to call the delegate safer.</p><pre>public Operate AritmeticOperation; //delegate object<br><br>public void Start()<br>{<br>    AritmeticOperation = Sum;<br>    //AritmeticOperation( 4, 5 ); //Delegate calling - first way<br>    AritmeticOperation?.Invoke( 4, 5 );// Delegate calling - second way<br>}<br><br>public int Sum( int a_num1, int a_num2 )<br>{<br>    return a_num1 + a_num2;<br>}</pre><p>As you’ve noticed, it’s very similar to the role of <em>student1</em>. <em>AritmeticOperation</em> is a function pointer to hold the reference of a method. I hope it is more clear now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*FFJuepMurb03auGQrPF65g.png" /></figure><p>I have run my script and tested on Unity. Look at the all code.</p><pre>using System;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class Program : MonoBehaviour<br>    {<br>        public delegate int Operate( int a, int b );<br><br>        public Operate AritmeticOperation;<br><br>        public void Start()<br>        {<br>            AritmeticOperation = Sum;<br><br>            //var result = AritmeticOperation(4, 5);<br>            var result = AritmeticOperation?.Invoke( 4, 5);<br>            <br>            UnityEngine.Debug.LogError( &quot;Result: &quot; + result );<br>        }<br><br>        public static int Sum( int a_num1, int a_num2 )<br>        {<br>            return a_num1 + a_num2;<br>        }<br>    }<br>}</pre><p>By the way, we can use a delegate for more than 1 methods. It is named <strong><em>multicast delegate</em></strong>. For example, I will create an extra function named <strong><em>Multiply</em></strong> which is the same signature with the delegate and add(+) it to AritmeticOperation. When it is run, we will see Invoke method return the last called method return value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*lpFIPVWwlyDAxwGMfThyCA.png" /></figure><pre>using System;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class Program : MonoBehaviour<br>    {<br>        public delegate int Operate( int a, int b );<br><br>        public Operate AritmeticOperation;<br><br>        public void Start()<br>        {<br>            AritmeticOperation += Sum;<br>            AritmeticOperation += Multiply;<br><br>            var result = AritmeticOperation?.Invoke( 4, 5);<br>            <br>            UnityEngine.Debug.LogError( &quot;Last: &quot; + result );<br>        }<br><br>        public static int Sum( int a_num1, int a_num2 )<br>        {<br>            var result = a_num1 + a_num2; <br>            UnityEngine.Debug.LogError( &quot;Summation: &quot; + result );<br>            return result;<br>        }<br><br>        public int Multiply(int a_num1, int a_num2)<br>        {<br>            var result = a_num1 * a_num2;<br>            UnityEngine.Debug.LogError( &quot;Multiplication: &quot; + result );<br>            return a_num1 * a_num2;<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*McLO7YzLvz6YXhVoUNCB0g.png" /></figure><p>Besides, we can remove(-) the method that we do not want to delegate anymore. (+) means subscribe and (-) means unsubscribe from a delegate. Let’s delete Multiply function. We have only Sum function. So, the result will be 9.</p><pre>using System;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class Program : MonoBehaviour<br>    {<br>        public delegate int Operate( int a, int b );<br><br>        public Operate AritmeticOperation;<br><br>        public void Start()<br>        {<br>            AritmeticOperation += Sum;<br>            AritmeticOperation += Multiply;<br><br>            var result1 = AritmeticOperation?.Invoke( 4, 5);<br>            UnityEngine.Debug.LogError( &quot;Before: &quot; + result1 );<br><br>            AritmeticOperation -= Multiply;<br><br>            var result2 = AritmeticOperation?.Invoke( 4, 5);<br>            UnityEngine.Debug.LogError( &quot;After: &quot; + result2 );<br>        }<br><br>        public static int Sum( int a_num1, int a_num2 )<br>        {<br>            return a_num1 + a_num2;<br>        }<br><br>        public int Multiply(int a_num1, int a_num2)<br>        {<br>            return a_num1 * a_num2;<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*Ikyp1uEQlElpFYvtAedzFQ.png" /></figure><p>Also, I would like to mention about generic delegates. If you know what generic it is you will probably understand this code very quickly.</p><pre>using System.Collections;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class GenericDelegate : MonoBehaviour<br>    {<br>        public delegate void Delegation&lt;T&gt;( T a_param1, T  a_param2);<br><br>        public void Start()<br>        {<br>            Delegation&lt;int&gt; m_intDelegate = new Delegation&lt;int&gt;( SumInt );<br>            m_intDelegate( 23, 41 );<br><br>            Delegation&lt;string &gt;m_stringDelegate = new Delegation&lt;string&gt;( SumString );<br>            m_stringDelegate(&quot;Rumeysa &quot;, &quot;Layık&quot;);<br>        }<br><br><br>        public void SumString( string a_param1, string a_param2 )<br>        {<br>            Debug.Log( a_param1 + a_param2 );<br>        }<br><br><br>        public void SumInt( int a_param1, int a_param2 )<br>        {<br>            Debug.Log( a_param1 + a_param2 );<br>        }<br>    }<br>}</pre><p>There are 4 kinds of delegates:</p><ul><li>Func Delegate</li><li>Action Delegate</li><li>Predicate Delegate</li><li>Anonymous Delegate</li></ul><h4>Func Delegate</h4><ul><li>This delegate takes a 1–16 input parameter and must have one return parameter.</li><li>Func is built-in delegate type.</li><li>Func delegate does not allow <strong>ref </strong>and <strong>out </strong>parameters. Syntax:</li></ul><pre>Func&lt;parameterlist,output value&gt; Object_name= new Func &lt;parameterlist,output value&gt;(method_name);</pre><p>Let’s give an example.</p><pre>using System;<br>using System.Collections;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class FuncDelegate : MonoBehaviour<br>    {<br>        static Func&lt;int, int, bool&gt; m_funcDelegate = new Func&lt;int, int, bool&gt;( FuncDelegate.Test );<br><br>        public void Start()<br>        {<br>            bool result = m_funcDelegate(25, 5);<br>            Debug.Log( result );<br>        }<br><br>        //This function controls the first number is divisible to the second number<br>        public static bool Test(int firstNumber, int secondNumber)<br>        {<br>            if (firstNumber &gt; secondNumber)<br>            {<br>                if (firstNumber % secondNumber == 0)<br>                    return true;<br>                else<br>                    return false;<br>            }<br>            else<br>            {<br>                return false;<br>            }<br>        }<br>    }<br>}</pre><h4>Action Delegate</h4><ul><li>The Action Delegate is needed when we need to invoke a method that doesn’t have any return type.</li><li>Action Delegate is capable of taking a maximum of 16 parameters as arguments, which means it has 16 overload methods.</li><li>Syntax:</li></ul><pre>Action&lt;parameter list&gt; Object_name= new Action &lt;parameter list&gt;(method_name);</pre><pre>using System;<br>using System.Collections;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class ActionDelegate : MonoBehaviour<br>    {<br>        static Action&lt;string, string&gt; actionDelegate = new Action&lt;string, string&gt;( Concat ); <br><br>        void Start()<br>        {<br>            actionDelegate( &quot;Night&quot;, &quot; Owl&quot;);<br>        }<br><br>        public static void Concat( string a, string b )<br>        {<br>            a += b;<br>            Debug.Log( &quot;Result: &quot;+ a );<br>        }<br>    }<br>}</pre><h4>Predicate Delegate</h4><ul><li>It represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. Syntax:</li></ul><pre>Predicate&lt;parameterlist&gt; Object_name= new Predicate&lt;parameterlist&gt;(method_name); * public delegate bool Predicate&lt;in T&gt;(T obj);</pre><pre>using System;<br>using System.Collections;<br>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class PredicateDelegate : MonoBehaviour<br>    {   <br>        Predicate&lt;int&gt; m_predicateDelegate = new Predicate&lt;int&gt;( PasswordLengthValidation );<br><br>        void Start()<br>        {<br>            bool result = m_predicateDelegate( 12547836 );<br>            Debug.Log( &quot;Result: &quot; + result );<br>        }<br><br>        public static bool PasswordLengthValidation( int number )<br>        {<br>            int count = 0;<br><br>            while( number &gt; 0 )<br>            {<br>                count++;<br>                number = number / 10;<br>            }<br><br>            Debug.Log(&quot;Count: &quot; + count);<br><br>            if ( count &gt; 8 || count &lt; 8 )<br>                return false;<br>            else<br>                return true;<br>        }<br>    }<br>}</pre><h3>EVENTS</h3><p>Events are a way for classes to notify other classes and objects that an event has occured. For example, if you click a button on Unity project OnClick event will be triggered automatically. It is provided by events.</p><p>Events:</p><ul><li>Can be multicast like delegates. More than one object subscribes to Event Handler.</li><li>Can be abstract but if you use accesscor event it cannot be.</li><li>Can be used in interfaces.</li><li>Can be defined as virtual and overwrite.</li></ul><h4>How to define:</h4><pre>using UnityEngine;<br><br>namespace Assets<br>{<br>    public class TestDelegate : MonoBehaviour<br>    {<br>        public delegate void Tester(int num);<br><br>        public event Tester TestDelegateObject;<br><br>        public void Start()<br>        {<br>            TestDelegateObject = ExampleFunction;<br><br>            TestDelegateObject(1254);<br>        }<br><br>        public void ExampleFunction(int a_num)<br>        {<br>            UnityEngine.Debug.LogError(&quot;Number1: &quot; + a_num);<br>        }<br><br>        public void ExampleFunction2(int a_num)<br>        {<br>            UnityEngine.Debug.LogError(&quot;Number2: &quot; + a_num);<br>        }<br>    }<br>}</pre><p>Events are declared using delegates which is compulsory to it. Delegate defines what kind of methods will be held by <em>TestDelegateObject</em>.</p><p>Let’s give an example from Super Mario game. You know, there is a normal point coins and some special mushrooms in the game. If you gain a special mushroom, Mario run faster, his clothe and the game music change and so on. How happen all them at the same time immediately? With the events it is very easy. Let’s look at.</p><pre>using System;<br>using System.Collections.Generic;<br><br>namespace ConsoleApp1<br>{<br>    public class SuperMario<br>    {<br>        public delegate void Mushroom( int a_mushroomPoint );<br>        public event Mushroom GainedMushroom; <br><br>        public void GainSpecialStar( int a_point )<br>        {<br>            GainedMushroom?.Invoke( a_point );<br>        }<br>    }<br>    <br>    public class Music<br>    {<br>        private List&lt;int&gt; musicIds = new List&lt;int&gt;() { 0, 1, 2 };<br>        private int m_currentMusicId = 0;<br><br>        public void ChangeMusic( int a_point )<br>        {<br>            var index = a_point / 10;<br>            m_currentMusicId = musicIds[index];<br>            <br>            Console.WriteLine( $&quot;Current music id is  {m_currentMusicId}&quot; );<br>        }<br>    }<br><br>    public class Speed<br>    {<br>        private int m_currentSpeed = 2;<br>        public void SpeedUp( int a_point )<br>        {<br>            m_currentSpeed *= a_point;  <br>            Console.WriteLine( $&quot;{ m_currentSpeed} is the new speed of the hero&quot; );<br>        }<br>    }<br>}</pre><p>I have created an delegate to define the event that can hold methods which have return nothing and take an integer parameter . Also, I have two classes <strong><em>Music</em></strong> and <strong><em>Speed </em></strong>which have the same signatured methods <strong><em>ChangeMusic</em></strong> and <strong><em>SpeedUp. ChangeMusic </em></strong>method will change the music and <strong><em>SpeedUp</em></strong> method will change Mario’s running speed by the mushroom point.</p><pre>namespace ConsoleApp1<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            SuperMario superMario = new SuperMario();<br><br>            Music music = new Music();<br><br>            Speed speed = new Speed();<br><br>            superMario.GainedMushroom += music.ChangeMusic; <br>            superMario.GainedMushroom += speed.SpeedUp;<br><br>            superMario.GainSpecialStar( 20 );<br><br>            System.Threading.Thread.Sleep(10000);<br>        }<br>    }<br>}</pre><p>I have subscribed these methods in Main function. When I triggered the event with the 20 point mushroom <strong><em>ChangeMusic</em></strong> and <strong><em>SpeedUp</em></strong> functions are called immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*KeSXmb1Ml-BihFcfIguCOA.png" /></figure><h4>What are the differences between a delegate and an event?</h4><ul><li>Events provide an abstraction to delegates.</li><li>Delegates can invoke externally but events can invoke internally</li></ul><blockquote>If an event is declared outside a class it will give an error.</blockquote><ul><li>An event cannot be sent as a method parameter.</li><li>Delegates support = operator but events don’t.</li></ul><p>It is a very crutial point, therefore, I would like to give an example.</p><pre>using System;<br><br><br>namespace ConsoleApp1<br>{<br>    public class Restaurant<br>    {<br>        public delegate void NewCustomer( string a_customer );<br><br>        public NewCustomer Customer;<br><br><br>        public void AddCustomer( string a_customerName )<br>        {<br>            Customer?.Invoke( a_customerName );<br>        }<br>    }<br><br>    public class Table<br>    {<br>        public void BookTable( string a_customerName )<br>        {<br>            Console.WriteLine( $&quot;{ a_customerName} booked a table&quot; );<br>        }<br>    }<br>}</pre><pre>namespace ConsoleApp1<br>{<br>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            Restaurant restaurant = new Restaurant();<br>            Table table = new Table();<br><br>            restaurant.Customer = table.BookTable;<br>            restaurant.AddCustomer( &quot;Nazım Hikmet&quot; );<br><br>            System.Threading.Thread.Sleep(5000);<br>        }<br>    }<br>}</pre><p>As you see, when we create a new Customer, booked a table for that customer. The output will be as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*ZnLVnXLnPzm609ElHhJZ8w.png" /></figure><p>On the other hand, event won’t allow it.</p><pre>using System;<br><br><br>namespace ConsoleApp1<br>{<br>    public class Restaurant<br>    {<br>        public delegate void NewCustomer( string a_customer );<br>        public event NewCustomer Customer;<br><br><br>        public void AddCustomer( string a_customerName )<br>        {<br>            Customer?.Invoke( a_customerName );<br>        }<br>    }<br><br>    public class Table<br>    {<br>        public void BookTable( string a_customerName )<br>        {<br>            Console.WriteLine( $&quot;{ a_customerName} booked a table&quot; );<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5NId5LcAiUEOXYCagMIZw.png" /></figure><p>It will give an error. Therefore you should use events with += operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*VB8G9UqllYeGge7RUHa1Wg.png" /></figure><p>We have come to the end of the blog. I hope it stand in hand for you and everything is clear. See you next blog :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b49edf04db8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>