Skip to content

Split View: 디지털 논리 설계 완전 가이드: 불 대수부터 CPU 설계까지

|

디지털 논리 설계 완전 가이드: 불 대수부터 CPU 설계까지

1. 디지털 시스템 개요

아날로그 vs 디지털

아날로그 신호는 연속적인 값을 가지며, 디지털 신호는 이산적인 값(0과 1)만을 사용합니다. 현대 전자 시스템의 대부분은 디지털 방식을 채택하고 있으며, 그 이유는 다음과 같습니다.

  • 노이즈 내성: 0과 1만 구분하므로 잡음에 강합니다.
  • 재현성: 복사 과정에서 신호 열화가 없습니다.
  • 처리 용이성: 불 대수를 이용해 논리적으로 처리 가능합니다.
  • 저장 용이성: 플립플롭, 메모리 등으로 완벽히 저장됩니다.

진법 변환

디지털 시스템에서는 2진수(Binary), 8진수(Octal), 16진수(Hexadecimal)를 자주 사용합니다.

10진수 → 2진수: 반복 나눗셈
  45 ÷ 2 = 22 나머지 1
  22 ÷ 2 = 11 나머지 0
  11 ÷ 2 =  5 나머지 1
   5 ÷ 2 =  2 나머지 1
   2 ÷ 2 =  1 나머지 0
   1 ÷ 2 =  0 나머지 1
  결과: 101101(2)
10진수2진수8진수16진수
0000000
5010155
10101012A
15111117F
16100002010

부호 표현

2의 보수(Two's Complement) 는 현대 컴퓨터에서 음수를 표현하는 표준 방식입니다.

+50000 0101
-5 계산:
  1의 보수: 1111 1010
  +1:       1111 1011-52의 보수 표현

8비트 2의 보수 범위: -128 ~ +127

BCD와 Gray 코드

  • BCD(Binary Coded Decimal): 각 10진 자리를 4비트로 표현 (예: 29 = 0010 1001)
  • Gray 코드: 인접한 코드 사이에 단 1비트만 변화 → 오류 최소화, 인코더에 활용

2. 불 대수 (Boolean Algebra)

기본 연산

불 대수의 세 가지 기본 연산:

  • AND (논리곱): A · B, A AND B. 둘 다 1일 때만 1.
  • OR (논리합): A + B, A OR B. 하나라도 1이면 1.
  • NOT (부정): A', NOT A. 0↔1 반전.

불 대수 법칙

교환 법칙:   A + B = B + A,      A · B = B · A
결합 법칙:   A + (B+C) = (A+B)+C
분배 법칙:   A · (B+C) = AB + AC
항등 원소:   A + 0 = A,   A · 1 = A
보원:        A + A' = 1,  A · A' = 0
멱등 법칙:   A + A = A,   A · A = A

드모르간(De Morgan) 정리:

(A · B)' = A' + B'
(A + B)' = A' · B'

이 정리는 NAND/NOR 구현과 논리 회로 단순화에 핵심적입니다.

표준형

  • SOP (Sum of Products, 곱의 합): 최소항의 합. 예: F = AB' + A'B + AB
  • POS (Product of Sums, 합의 곱): 최대항의 곱. 예: F = (A+B)(A'+C)

3. 논리 게이트

기본 게이트 진리표

AND 게이트:          OR 게이트:           NOT 게이트:
A  B  A·B            A  B  A+B            A  A'
0  0   0             0  0   0             0   1
0  1   0             0  1   1             1   0
1  0   0             1  0   1
1  1   1             1  1   1

NAND 게이트:         NOR 게이트:
A  B  (A·B)'         A  B  (A+B)'
0  0    1            0  0    1
0  1    1            0  1    0
1  0    1            1  0    0
1  1    0            1  1    0

XOR 게이트:          XNOR 게이트:
A  B  AB            A  B  (AB)'
0  0   0             0  0    1
0  1   1             0  1    0
1  0   1             1  0    0
1  1   0             1  1    1

NAND/NOR의 범용성 (Universal Gate)

NAND 게이트 하나만으로 NOT, AND, OR 모두 구현 가능합니다.

NOT A  = A NAND A
A AND B = (A NAND B) NAND (A NAND B)
A OR B  = (A NAND A) NAND (B NAND B)

이 특성 덕분에 실제 칩 제작 시 NAND 게이트만으로 모든 논리를 구현할 수 있어 제조 공정이 단순해집니다. NOR 게이트도 동일한 범용성을 가집니다.

CMOS 구현 개요

현대 디지털 회로의 대부분은 CMOS(Complementary MOS) 기술로 구현됩니다.

  • NMOS 트랜지스터: 게이트에 HIGH 인가 시 ON (풀다운)
  • PMOS 트랜지스터: 게이트에 LOW 인가 시 ON (풀업)
  • CMOS NOT 게이트: PMOS + NMOS 직렬 구성
  • 정적 전력 소비 거의 0 → 저전력 장점

4. 카르노 맵 (Karnaugh Map)

카르노 맵은 불 대수 표현을 시각적으로 단순화하는 도구입니다. 인접한 셀끼리 묶어(그레이 코드 순서) 항을 최소화합니다.

4변수 카르노 맵 예시

        CD
AB    00  01  11  10
00  [  1   0   1   1 ]
01  [  1   1   1   0 ]
11  [  0   1   1   0 ]
10  [  0   0   1   1 ]

묶음 규칙

  1. 셀을 1, 2, 4, 8, 16개 단위로만 묶습니다 (2의 거듭제곱).
  2. 묶음은 직사각형(정사각형 포함) 형태여야 합니다.
  3. 맵은 상하좌우로 연결됩니다 (토러스 형태).
  4. 최대한 크게, 최소한의 묶음 수로 묶어야 합니다.
  5. Don't care(X) 조건은 묶음에 포함시킬 수 있습니다.

필수 소항 (Prime Implicant)

더 이상 확장할 수 없는 최대 묶음을 소항(Prime Implicant) 이라 하고, 해당 최소항을 포함하는 소항이 오직 하나일 때 필수 소항(Essential PI) 이라 합니다. 최소화된 SOP는 모든 필수 소항을 포함해야 합니다.


5. 조합 논리 회로

조합 회로의 출력은 오직 현재 입력에만 의존합니다 (기억 없음).

반가산기와 전가산기

반가산기 (Half Adder):
  (Sum) S = AB
  올림(Carry) C = A · B

전가산기 (Full Adder):
  S = ABCin
  Cout = AB + Cin(AB)

전가산기를 직렬 연결하면 병렬 가산기(Ripple Carry Adder) 가 됩니다. 올림 신호가 순차적으로 전파되므로 속도가 느리지만 구조가 단순합니다. 고속 연산에는 올림 예측 가산기(Carry Lookahead Adder) 를 사용합니다.

멀티플렉서 (MUX)

n개의 선택 신호로 2^n개의 입력 중 하나를 선택해 출력합니다.

4:1 MUX (S1, S0 = 선택 신호):
  S1=0, S0=0Y = I0
  S1=0, S0=1Y = I1
  S1=1, S0=0Y = I2
  S1=1, S0=1Y = I3

MUX는 조합 함수 구현에도 활용됩니다. 2^n : 1 MUX로 n변수 임의 함수 구현 가능.

인코더와 디코더

  • 인코더: 2^n 입력을 n비트 이진 코드로 변환 (예: 10-to-4 우선순위 인코더)
  • 디코더: n비트 이진 코드를 최대 2^n개의 출력으로 변환 (예: 3-to-8 디코더)

디코더 + OR 게이트 조합으로 임의의 조합 함수 구현 가능 → 최소항의 합(SOP) 직접 구현.


6. 순서 논리 회로

순서 회로의 출력은 현재 입력뿐 아니라 이전 상태(메모리) 에도 의존합니다.

래치 (Latch)

SR 래치 는 Set-Reset 입력으로 상태를 저장하는 가장 기본적인 메모리 소자입니다.

SR 래치 진리표:
S  R  Q(다음)
0  0  Q(유지)
1  0  1 (Set)
0  1  0 (Reset)
1  1  불확정 (금지)

D 래치 는 SR 래치의 금지 상태를 제거한 버전으로, Enable 신호가 HIGH일 때 D 입력을 그대로 저장합니다.

플립플롭 (Flip-Flop)

플립플롭은 에지 트리거(edge-triggered) 방식으로 클록의 상승 또는 하강 에지에서만 상태가 변합니다.

D 플립플롭:  Q(다음) = D
JK 플립플롭:
  J=0, K=0Q(유지)
  J=1, K=0Q=1 (Set)
  J=0, K=1Q=0 (Reset)
  J=1, K=1Q' (Toggle)
T 플립플롭:
  T=0Q(유지)
  T=1Q' (Toggle)

JK 플립플롭은 모든 입력 조합이 유효하며, T 플립플롭은 카운터 설계에 편리합니다.


7. 레지스터와 카운터

시프트 레지스터

여러 플립플롭을 직렬로 연결하여 데이터를 시프트(이동)하는 회로입니다.

  • SISO: Serial In Serial Out — 직렬 입력, 직렬 출력
  • SIPO: Serial In Parallel Out — 직렬 입력, 병렬 출력
  • PISO: Parallel In Serial Out — 병렬 입력, 직렬 출력
  • PIPO: Parallel In Parallel Out — 병렬 입력, 병렬 출력

시프트 레지스터의 응용: 직병렬 변환, CRC 계산, 난수 생성(LFSR), 곱셈/나눗셈(2의 거듭제곱).

카운터

3비트 비동기 카운터 (Ripple Counter):
  3개의 T 플립플롭 직렬 연결
  012345670 ...
  단점: 올림 전파 지연(ripple delay) 발생

3비트 동기 카운터:
  모든 플립플롭이 공통 클록 사용
  장점: 출력이 동시에 변화, 고속 동작 가능

모듈로-N 카운터 는 0부터 N-1까지 순환합니다. 예: 10진 카운터(Decade Counter)는 0~9 순환.


8. 유한 상태 기계 (FSM)

FSM은 순서 회로의 추상적 모델로, 디지털 시스템 설계의 핵심입니다.

무어 기계 vs 밀리 기계

  • 무어 기계(Moore Machine): 출력이 현재 상태에만 의존. 상태 다이어그램에서 출력을 상태 안에 표시.
  • 밀리 기계(Mealy Machine): 출력이 현재 상태 + 입력에 의존. 전이(transition) 위에 입력/출력 표시.

자판기 FSM 예시

상태: S0(0), S1(100), S2(200), S3(300원 → 음료 출력)
입력: 100(A), 200(B)

상태 전이:
  S0 --A--> S1
  S0 --B--> S2
  S1 --A--> S2
  S1 --B--> S3(출력)
  S2 --A--> S3(출력)
  S2 --B--> S3(출력, 100원 거스름돈)

FSM 설계 절차

  1. 문제 분석 → 상태 정의
  2. 상태 다이어그램 작성
  3. 상태 테이블 작성
  4. 상태 인코딩 (이진 코드 할당)
  5. 다음 상태 함수와 출력 함수 도출
  6. 카르노 맵으로 최소화
  7. 플립플롭과 게이트로 구현

9. Verilog HDL 기초

Verilog HDL(Hardware Description Language)은 디지털 회로를 소프트웨어처럼 기술하는 언어입니다.

모듈 구조

module module_name (
    input  wire clk,
    input  wire reset,
    input  wire [3:0] data_in,
    output reg  [3:0] data_out
);
    // 내부 신호 선언
    wire [3:0] temp;

    // 조합 회로: assign
    assign temp = data_in & 4'b1111;

    // 순서 회로: always
    always @(posedge clk or posedge reset) begin
        if (reset)
            data_out <= 4'b0000;
        else
            data_out <= temp;
    end
endmodule

D 플립플롭

module d_ff (
    input  wire clk,
    input  wire reset,
    input  wire d,
    output reg  q
);
    always @(posedge clk or posedge reset) begin
        if (reset)
            q <= 1'b0;
        else
            q <= d;
    end
endmodule

4비트 카운터

module counter_4bit (
    input  wire clk,
    input  wire reset,
    output reg  [3:0] count
);
    always @(posedge clk or posedge reset) begin
        if (reset)
            count <= 4'b0000;
        else
            count <= count + 1'b1;
    end
endmodule

테스트벤치 (Testbench)

module tb_counter;
    reg  clk, reset;
    wire [3:0] count;

    // DUT(Device Under Test) 인스턴스화
    counter_4bit uut (
        .clk(clk),
        .reset(reset),
        .count(count)
    );

    // 클록 생성: 10ns 주기
    initial clk = 0;
    always #5 clk = ~clk;

    initial begin
        reset = 1;
        #20 reset = 0;
        #200 $finish;
    end

    initial begin
        $monitor("t=%0t reset=%b count=%b", $time, reset, count);
    end
endmodule

데이터 타입

타입설명사용처
wire연결선, 구동값 유지assign, 포트 연결
reg값 저장 가능한 변수always 블록 내부
integer정수형시뮬레이션, 루프
parameter상수모듈 파라미터화

10. FPGA 기초

FPGA vs ASIC vs 마이크로프로세서

구분FPGAASICMCU/CPU
재구성가능불가소프트웨어 변경 가능
성능중간~고성능최고범용
개발 비용중간매우 높음낮음
대량 생산 비용높음낮음낮음
병렬 처리탁월탁월제한적
용도프로토타입, 중소량대량 생산범용 제어

FPGA 내부 구조

  • CLB(Configurable Logic Block): LUT + 플립플롭 + MUX의 조합
  • LUT(Look-Up Table): n입력 LUT는 임의의 n변수 함수 구현 가능 (진리표 직접 저장)
  • IOB(I/O Block): 외부 핀과의 인터페이스, 다양한 전압/프로토콜 지원
  • 블록 RAM(BRAM): 내장 메모리 블록
  • DSP 블록: 고속 곱셈/가산기, 신호 처리 전용
  • PLL/DCM: 클록 관리, 주파수 합성

FPGA 설계 플로우

1. 설계 입력 (HDL 코드 작성 / 스케매틱)
2. 합성 (Synthesis) → 게이트 레벨 넷리스트
3. 구현 (Implementation)
   ├── 매핑 (Map)FPGA 리소스에 배치
   ├── 배치 (Place) → 물리적 위치 결정
   └── 배선 (Route) → 연결선 결정
4. 타이밍 분석 (Timing Analysis)
5. 비트스트림 생성 (Bitstream Generation)
6. FPGA 프로그래밍

대표 FPGA 제조사

  • AMD-Xilinx: Spartan (저가), Artix, Kintex, Virtex (고성능), Zynq (ARM+FPGA)
  • Intel (Altera): Cyclone (저가), Arria, Stratix (고성능)
  • Lattice Semiconductor: iCE40 (초저전력, 오픈소스 도구 지원)

11. CPU 기초 설계

ALU (산술논리연산장치)

ALU는 CPU의 핵심으로, 산술 연산과 논리 연산을 수행합니다.

ALU 입력:
  A, B: 피연산자 (n비트)
  OpCode: 연산 선택

ALU 출력:
  Result: 연산 결과 (n비트)
  Zero: 결과가 0이면 1
  Carry: 올림 발생 시 1
  Overflow: 오버플로우 발생 시 1
  Negative: 결과가 음수이면 1

지원 연산 예시:
  000A + B (가산)
  001A - B (감산)
  010A AND B
  011A OR B
  100A XOR B
  101NOT A
  110A << 1 (좌측 시프트)
  111A >> 1 (우측 시프트)

레지스터 파일

범용 레지스터의 집합으로, 두 개의 읽기 포트와 하나의 쓰기 포트를 가집니다.

module register_file (
    input  wire clk,
    input  wire we,
    input  wire [4:0] rs1, rs2, rd,
    input  wire [31:0] write_data,
    output wire [31:0] read_data1,
    output wire [31:0] read_data2
);
    reg [31:0] regs [0:31];

    assign read_data1 = regs[rs1];
    assign read_data2 = regs[rs2];

    always @(posedge clk) begin
        if (we && rd != 0)
            regs[rd] <= write_data;
    end
endmodule

단순 CPU 데이터패스

명령어 페치(IF)PC → 명령어 메모리
명령어 디코드(ID) → 레지스터 읽기, 제어 신호 생성
실행(EX)ALU 연산
메모리 접근(MEM) → 데이터 메모리 읽기/쓰기
쓰기(WB) → 결과를 레지스터 파일에 저장

파이프라이닝

단일 사이클 CPU를 5단계 파이프라인으로 나누면 처리량(throughput)이 크게 향상됩니다.

클록:   1  2  3  4  5  6  7  8  9
명령1: IF ID EX ME WB
명령2:    IF ID EX ME WB
명령3:       IF ID EX ME WB
명령4:          IF ID EX ME WB
명령5:             IF ID EX ME WB

파이프라인 위험(Hazard): 구조적 위험, 데이터 위험(RAW, WAR, WAW), 제어 위험을 포워딩, 스톨, 분기 예측으로 해결합니다.


12. AI 하드웨어와의 연결

GPU의 디지털 논리 구조

GPU는 수천 개의 소형 ALU 코어(CUDA 코어, SIMD 유닛)를 병렬로 배치한 구조입니다. 행렬 곱셈(딥러닝의 핵심 연산)을 병렬로 처리하는 데 최적화되어 있습니다.

  • NVIDIA Tensor Core: 혼합 정밀도(FP16 × FP16 + FP32) 행렬 연산 가속
  • 수천 개의 코어가 동일한 명령을 병렬 실행 (SIMT 아키텍처)

TPU와 NPU

  • TPU(Tensor Processing Unit): Google이 설계한 행렬 연산 전용 ASIC. 시스톨릭 어레이(Systolic Array) 구조로 MAC(Multiply-Accumulate) 연산 대규모 병렬화.
  • NPU(Neural Processing Unit): 모바일/엣지 디바이스용 AI 가속기. 애플 Neural Engine, 퀄컴 Hexagon DSP 등.

FPGA를 이용한 AI 가속

FPGA는 신경망 추론(inference) 가속에 활용됩니다.

  • 낮은 레이턴시: 실시간 처리 요구 시스템에 적합
  • 유연성: 모델 변경 시 비트스트림 재로딩으로 대응
  • 예: 데이터센터 내 FPGA 추론 가속 (Microsoft Project Brainwave)

뉴로모픽 컴퓨팅

뇌의 뉴런-시냅스 구조를 하드웨어로 모방한 컴퓨팅 패러다임입니다.

  • Intel Loihi: 스파이킹 뉴럴 네트워크(SNN) 전용 칩
  • IBM TrueNorth: 100만 뉴런, 2억 5600만 시냅스 온칩 구현
  • 초저전력 / 이벤트 기반 처리 → 엣지 AI에 유망

13. 학습 로드맵

[기초]
  불 대수 → 논리 게이트 → 카르노 맵
[조합 회로]
  가산기, MUX, 디코더, 인코더
[순서 회로]
  래치 → 플립플롭 → 레지스터 → 카운터
[시스템 설계]
  FSM → 데이터패스 → 제어 유닛
[HDL/FPGA]
  Verilog → 시뮬레이션 → FPGA 구현
[CPU/SoC]
  ALU → 파이프라인 → 메모리 계층
[AI 하드웨어]
  GPU 아키텍처 → TPU/NPUFPGA 가속

퀴즈

Q1. NAND 게이트가 범용 게이트(Universal Gate)라고 불리는 이유는?

정답: NAND 게이트만으로 AND, OR, NOT 모든 기본 논리 게이트를 구현할 수 있기 때문입니다.

설명:

  • NOT A = A NAND A
  • A AND B = (A NAND B) NAND (A NAND B)
  • A OR B = (A NAND A) NAND (B NAND B)

따라서 NAND 게이트만으로 모든 불 함수를 구현할 수 있습니다. NOR 게이트도 동일하게 범용 게이트입니다.

Q2. 2의 보수 방식에서 8비트로 표현할 수 있는 음수의 최솟값은?

정답: -128 (즉, 10000000(2))

설명: 8비트 2의 보수에서 표현 범위는 -128 ~ +127입니다. 최상위 비트(MSB)가 1이면 음수이며, -128은 10000000(2)으로 표현됩니다. +128은 표현 불가능하여 비대칭 범위를 가집니다.

Q3. D 플립플롭과 D 래치의 차이점은 무엇인가요?

정답: D 래치는 Enable 신호가 HIGH인 동안 계속 입력을 반영하고(레벨 트리거), D 플립플롭은 클록의 에지(상승 또는 하강)에서만 입력을 저장합니다(에지 트리거).

설명: 래치는 Enable=1인 동안 투명(transparent)하게 동작합니다. 플립플롭은 에지에서만 샘플링하므로 타이밍 제어가 엄격하며, 동기 회로 설계에서 표준으로 사용됩니다.

Q4. 카르노 맵에서 Don't care 조건을 사용하는 이유는 무엇인가요?

정답: 입력 조합이 실제로 발생하지 않는 경우, 해당 출력값을 0이나 1 중 회로 최소화에 유리한 방향으로 자유롭게 선택할 수 있기 때문입니다.

설명: 예를 들어 BCD 입력(09)에서 10101111은 사용되지 않습니다. 이 6개 조합을 Don't care(X)로 처리하면, 카르노 맵에서 더 크게 묶을 수 있어 게이트 수가 줄어들고 회로가 단순해집니다.

Q5. 파이프라인 CPU에서 데이터 위험(Data Hazard)이란 무엇이며, 어떻게 해결하나요?

정답: 이전 명령어의 결과를 다음 명령어가 아직 완료되기 전에 사용하려 할 때 발생하는 충돌입니다.

해결 방법:

  • 포워딩(Forwarding/Bypassing): ALU 출력을 다음 단계의 입력으로 직접 연결 (가장 일반적)
  • 스톨(Stall/Bubble 삽입): 의존 관계가 해결될 때까지 파이프라인을 정지
  • 컴파일러 스케줄링: 의존 관계 없는 명령어를 사이에 배치

참고 자료

Digital Logic Design Complete Guide: From Boolean Algebra to CPU Design

1. Introduction to Digital Systems

Analog vs Digital

Analog signals carry continuous values while digital signals use only discrete states — 0 and 1. Modern electronics overwhelmingly favors digital systems for several key reasons:

  • Noise immunity: Only two levels to distinguish, making the system highly resistant to electrical noise.
  • Perfect reproduction: Copying digital data introduces no signal degradation.
  • Logical processing: Boolean algebra provides a rigorous mathematical foundation.
  • Storage: Flip-flops and memory cells store state reliably and indefinitely.

Number System Conversions

Digital systems regularly use binary (base-2), octal (base-8), and hexadecimal (base-16) representations.

Decimal to Binary — repeated division by 2:
  45 ÷ 2 = 22 remainder 1
  22 ÷ 2 = 11 remainder 0
  11 ÷ 2 =  5 remainder 1
   5 ÷ 2 =  2 remainder 1
   2 ÷ 2 =  1 remainder 0
   1 ÷ 2 =  0 remainder 1
  Result: 101101 (binary)
DecimalBinaryOctalHex
0000000
5010155
10101012A
15111117F
16100002010

Signed Number Representation

Two's complement is the universal standard for representing negative integers in hardware.

+50000 0101
Computing -5:
  One's complement:  1111 1010
  Add 1:             1111 1011-5 in two's complement

Range for an 8-bit two's complement number: -128 to +127.

BCD and Gray Code

  • BCD (Binary Coded Decimal): Each decimal digit is encoded as 4 bits. Example: 29 = 0010 1001.
  • Gray code: Adjacent codewords differ by exactly one bit, minimizing transition errors in mechanical encoders and analog-to-digital converters.

2. Boolean Algebra

Fundamental Operations

Three primitive operations form the foundation of Boolean algebra:

  • AND (logical product): A · B — output is 1 only when both inputs are 1.
  • OR (logical sum): A + B — output is 1 when at least one input is 1.
  • NOT (complement): A' — inverts the input.

Boolean Laws

Commutative:   A + B = B + A,      A · B = B · A
Associative:   A + (B+C) = (A+B) + C
Distributive:  A · (B+C) = AB + AC
Identity:      A + 0 = A,  A · 1 = A
Complement:    A + A' = 1, A · A' = 0
Idempotent:    A + A = A,  A · A = A

De Morgan's Theorems — essential for NAND/NOR-based implementations:

(A · B)' = A' + B'
(A + B)' = A' · B'

Canonical Forms

  • SOP (Sum of Products): Sum of minterms. Example: F = AB' + A'B + AB
  • POS (Product of Sums): Product of maxterms. Example: F = (A+B)(A'+C)

Any Boolean function can be expressed in either canonical form, making these forms the starting point for logic minimization.


3. Logic Gates

Truth Tables for All Basic Gates

AND Gate:            OR Gate:             NOT Gate:
A  B  A·B            A  B  A+B            A  A'
0  0   0             0  0   0             0   1
0  1   0             0  1   1             1   0
1  0   0             1  0   1
1  1   1             1  1   1

NAND Gate:           NOR Gate:
A  B  (A·B)'         A  B  (A+B)'
0  0    1            0  0    1
0  1    1            0  1    0
1  0    1            1  0    0
1  1    0            1  1    0

XOR Gate:            XNOR Gate:
A  B  AB            A  B  (AB)'
0  0   0             0  0    1
0  1   1             0  1    0
1  0   1             1  0    0
1  1   0             1  1    1

Universal Gates (NAND and NOR)

NAND alone can implement any Boolean function:

NOT A   = A NAND A
A AND B = (A NAND B) NAND (A NAND B)
A OR B  = (A NAND A) NAND (B NAND B)

This universality is commercially significant — an entire chip family can be fabricated from a single cell type, simplifying the manufacturing process. NOR gates are equally universal.

CMOS Implementation Overview

Modern digital ICs use CMOS (Complementary Metal-Oxide-Semiconductor) technology:

  • NMOS transistor: Turns ON when gate is HIGH (pull-down network).
  • PMOS transistor: Turns ON when gate is LOW (pull-up network).
  • CMOS inverter: series PMOS + NMOS between VDD and GND.
  • Static power consumption is nearly zero, which explains CMOS dominance in low-power design.

4. Karnaugh Maps

The Karnaugh map (K-map) provides a visual, systematic method for minimizing Boolean expressions by identifying groups of adjacent 1s.

4-Variable K-map Example

          CD
AB      00  01  11  10
00  [    1   0   1   1  ]
01  [    1   1   1   0  ]
11  [    0   1   1   0  ]
10  [    0   0   1   1  ]

Grouping Rules

  1. Group sizes must be powers of 2: 1, 2, 4, 8, or 16.
  2. Groups must be rectangular (including squares).
  3. The map wraps around on all edges (toroidal topology).
  4. Use the fewest, largest possible groups.
  5. Don't-care conditions (X) may be included in groups to enlarge them.

Prime Implicants

A prime implicant is a group that cannot be further expanded. An essential prime implicant covers at least one minterm not covered by any other prime implicant — it must appear in the minimal SOP expression.


5. Combinational Logic Circuits

A combinational circuit's output depends solely on current inputs — there is no internal state or memory.

Half Adder and Full Adder

Half Adder:
  Sum   S = AB
  Carry C = A · B

Full Adder:
  Sum   S    = ABCin
  Carry Cout = AB + Cin(AB)

Cascading full adders creates a Ripple Carry Adder — simple but slow because carry propagates serially. The Carry Lookahead Adder (CLA) computes carries in parallel for high-speed arithmetic.

Multiplexer (MUX)

A 2-to-n-input MUX selects one of 2^n data inputs using n select lines.

4-to-1 MUX (select lines S1, S0):
  S1=0, S0=0Y = I0
  S1=0, S0=1Y = I1
  S1=1, S0=0Y = I2
  S1=1, S0=1Y = I3

A 2^n-to-1 MUX can implement any n-variable Boolean function directly.

Encoders and Decoders

  • Encoder: Converts 2^n input lines to an n-bit binary code (e.g., priority encoder handles multiple simultaneous inputs).
  • Decoder: Converts an n-bit code to up to 2^n output lines (e.g., 3-to-8 decoder asserts one of eight outputs).

A decoder combined with OR gates directly implements any sum-of-minterms (SOP) expression.


6. Sequential Logic Circuits

Sequential circuits depend on both current inputs and internal state (memory). They are the building blocks of registers, counters, and processors.

Latches

The SR latch is the simplest storage element, built from cross-coupled NAND or NOR gates.

SR Latch truth table:
S  R  Q(next)
0  0  Q (no change)
1  0  1 (Set)
0  1  0 (Reset)
1  1  Undefined (forbidden)

The D latch eliminates the forbidden state by tying S = D and R = D'. When Enable is HIGH, Q tracks D; when Enable is LOW, Q retains its value.

Flip-Flops

Flip-flops are edge-triggered — state changes only on the rising or falling clock edge, not during the entire clock period. This strict timing discipline is essential for synchronous design.

D flip-flop:   Q(next) = D

JK flip-flop:
  J=0, K=0Q (hold)
  J=1, K=0Q = 1 (Set)
  J=0, K=1Q = 0 (Reset)
  J=1, K=1Q' (Toggle)

T flip-flop:
  T=0Q (hold)
  T=1Q' (Toggle)

The JK flip-flop has no undefined input combination. The T flip-flop is the natural choice for counter design.


7. Registers and Counters

Shift Registers

Shift registers chain multiple flip-flops so data moves (shifts) through them with each clock cycle.

  • SISO (Serial In, Serial Out): Data enters and leaves serially.
  • SIPO (Serial In, Parallel Out): Serial data is loaded, then all bits are read simultaneously.
  • PISO (Parallel In, Serial Out): Parallel data is loaded, then transmitted bit by bit.
  • PIPO (Parallel In, Parallel Out): Complete parallel load and parallel read.

Applications: serial-to-parallel conversion, CRC generation, pseudo-random number generators (LFSR), and fast multiply/divide by powers of 2.

Counters

3-bit Asynchronous (Ripple) Counter:
  Three T flip-flops chained in series.
  012345670 ...
  Drawback: ripple delay accumulates with each stage.

3-bit Synchronous Counter:
  All flip-flops share a common clock.
  All outputs change simultaneously → no ripple delay.

A Modulo-N counter cycles through 0 to N-1. Example: a BCD counter (modulo-10) cycles 0 through 9 and is widely used in digital clocks.


8. Finite State Machines (FSM)

An FSM is the abstract model underlying all sequential logic systems. It consists of a finite set of states, transition conditions, and outputs.

Moore vs Mealy Machines

  • Moore machine: Output depends only on the current state. Output labels appear inside state bubbles.
  • Mealy machine: Output depends on current state AND inputs. Output labels appear on transitions.

Mealy machines generally require fewer states than equivalent Moore machines.

Vending Machine FSM Example

States: S0 (0 cents), S1 (10 cents), S2 (20 cents), S3 (dispense)
Inputs: D (dime = 10c), Q (quarter = 25c)

Transitions:
  S0 --D--> S1
  S0 --Q--> S2 (with 5c change output)
  S1 --D--> S2
  S1 --Q--> S3 (dispense, 5c change)
  S2 --D--> S3 (dispense)
  S2 --Q--> S3 (dispense, 15c change)

FSM Design Procedure

  1. Analyze the problem and define all states.
  2. Draw the state diagram.
  3. Construct the state table (next-state and output).
  4. Assign binary codes to states (state encoding).
  5. Derive next-state and output Boolean equations.
  6. Minimize with Karnaugh maps.
  7. Implement with flip-flops and combinational gates.

9. Verilog HDL Fundamentals

Verilog HDL (Hardware Description Language) allows designers to describe digital circuits textually, enabling simulation and automated synthesis to physical gates.

Module Structure

module module_name (
    input  wire        clk,
    input  wire        reset,
    input  wire [3:0]  data_in,
    output reg  [3:0]  data_out
);
    wire [3:0] temp;

    // Combinational logic — assign
    assign temp = data_in & 4'b1111;

    // Sequential logic — always
    always @(posedge clk or posedge reset) begin
        if (reset)
            data_out <= 4'b0000;
        else
            data_out <= temp;
    end
endmodule

D Flip-Flop

module d_ff (
    input  wire clk,
    input  wire reset,
    input  wire d,
    output reg  q
);
    always @(posedge clk or posedge reset) begin
        if (reset)
            q <= 1'b0;
        else
            q <= d;
    end
endmodule

4-bit Synchronous Counter

module counter_4bit (
    input  wire       clk,
    input  wire       reset,
    output reg  [3:0] count
);
    always @(posedge clk or posedge reset) begin
        if (reset)
            count <= 4'b0000;
        else
            count <= count + 1'b1;
    end
endmodule

Testbench

module tb_counter;
    reg        clk, reset;
    wire [3:0] count;

    counter_4bit uut (
        .clk(clk),
        .reset(reset),
        .count(count)
    );

    // 10 ns clock period
    initial clk = 0;
    always #5 clk = ~clk;

    initial begin
        reset = 1;
        #20 reset = 0;
        #200 $finish;
    end

    initial begin
        $monitor("t=%0t reset=%b count=%b", $time, reset, count);
    end
endmodule

Verilog Data Types Summary

TypeDescriptionTypical Use
wireCombinational net, holds driven valueassign statements, port connections
regCan store a value between updatesInside always blocks
integer32-bit signed integerLoop variables, simulation
parameterNamed constantParameterizing module widths

10. FPGA Fundamentals

FPGA vs ASIC vs Microprocessor

AttributeFPGAASICMCU / CPU
ReconfigurableYesNoVia software
Peak performanceMedium–HighHighestGeneral purpose
NRE costNoneVery highLow
Unit cost (high volume)HighVery lowLow
ParallelismExcellentExcellentLimited
Best forPrototyping, moderate volumeMass productionControl tasks

FPGA Internal Architecture

  • CLB (Configurable Logic Block): Contains LUTs, flip-flops, and MUXes.
  • LUT (Look-Up Table): An n-input LUT implements any n-variable Boolean function by storing the truth table directly in SRAM.
  • IOB (I/O Block): Interface between the FPGA fabric and external pins; supports multiple voltage standards and I/O protocols.
  • Block RAM (BRAM): Dedicated on-chip memory blocks for storing data arrays.
  • DSP Blocks: Hardened fast multiply-accumulate units optimized for signal processing.
  • PLL / Clock Management: On-chip phase-locked loops for frequency synthesis and clock distribution.

FPGA Design Flow

1. Design Entry — write HDL (Verilog/VHDL) or use a schematic editor
2. Synthesis — convert HDL to a technology-independent gate-level netlist
3. Implementation
   ├── Technology Mapping — map netlist to FPGA primitives (LUTs, FFs)
   ├── Placement (Place) — assign primitives to physical FPGA resources
   └── Routing (Route) — connect placed elements with on-chip wires
4. Timing Analysis — verify all setup/hold constraints are met
5. Bitstream Generation — produce the programming file
6. Device Programming — download bitstream to FPGA via JTAG

Leading FPGA Vendors

  • AMD-Xilinx: Spartan (cost-optimized), Artix, Kintex, Virtex (high-performance), Zynq (ARM + FPGA SoC).
  • Intel (Altera): Cyclone (low cost), Arria (mid-range), Stratix (high-end).
  • Lattice Semiconductor: iCE40 (ultra-low power, open-source toolchain available).

11. Basic CPU Design

ALU (Arithmetic Logic Unit)

The ALU is the computational heart of any processor.

ALU Inputs:
  A, B      — n-bit operands
  OpCode    — selects the operation

ALU Outputs:
  Result    — n-bit result
  Zero      — asserted when Result = 0
  Carry     — asserted on unsigned overflow
  Overflow  — asserted on signed overflow
  Negative  — asserted when Result < 0

Example operations:
  000A + B (addition)
  001A - B (subtraction)
  010A AND B
  011A OR B
  100A XOR B
  101NOT A
  110A << 1 (logical left shift)
  111A >> 1 (logical right shift)

Register File

A register file provides fast, on-chip storage for operands and results. A typical 32-register file has two read ports and one write port.

module register_file (
    input  wire        clk,
    input  wire        we,
    input  wire [4:0]  rs1, rs2, rd,
    input  wire [31:0] write_data,
    output wire [31:0] read_data1,
    output wire [31:0] read_data2
);
    reg [31:0] regs [0:31];

    assign read_data1 = regs[rs1];
    assign read_data2 = regs[rs2];

    always @(posedge clk) begin
        if (we && rd != 0)
            regs[rd] <= write_data;
    end
endmodule

Simple CPU Datapath

IFInstruction Fetch: read instruction from memory at PC
IDInstruction Decode: read registers, generate control signals
EXExecute: ALU performs computation
MEMMemory Access: load/store data memory
WBWrite Back: write result to register file

Pipelining

A 5-stage pipeline overlaps execution of multiple instructions to increase throughput:

Cycle:      1   2   3   4   5   6   7   8   9
Instr 1:   IF  ID  EX  ME  WB
Instr 2:       IF  ID  EX  ME  WB
Instr 3:           IF  ID  EX  ME  WB
Instr 4:               IF  ID  EX  ME  WB
Instr 5:                   IF  ID  EX  ME  WB

Pipeline hazards disrupt ideal throughput:

  • Structural: Two instructions need the same hardware resource simultaneously.
  • Data (RAW/WAR/WAW): An instruction reads a value not yet written by a previous instruction. Resolved with forwarding, stalls, or compiler scheduling.
  • Control: Branch outcome unknown until late in the pipeline. Resolved with branch prediction, delayed branching, or speculative execution.

12. Connecting to AI Hardware

GPU Digital Logic Architecture

A modern GPU contains thousands of small ALU cores (CUDA cores, SIMD lanes) operating in parallel. This massive parallelism maps perfectly onto the matrix multiplications that dominate deep learning workloads.

  • NVIDIA Tensor Cores: Perform mixed-precision (FP16 × FP16 accumulate to FP32) matrix operations in a single clock cycle.
  • SIMT execution model: Thousands of threads execute the same instruction on different data simultaneously.

TPU and NPU

  • TPU (Tensor Processing Unit): Google's custom ASIC built around a systolic array of MAC (Multiply-Accumulate) units. Designed exclusively for neural network inference and training.
  • NPU (Neural Processing Unit): Edge-device AI accelerators. Examples: Apple Neural Engine, Qualcomm Hexagon DSP, Samsung Exynos NPU.

FPGA-Based AI Acceleration

FPGAs occupy a useful niche in AI acceleration:

  • Low latency: Suitable for real-time inference (autonomous driving, industrial vision).
  • Flexibility: Reconfigure the bitstream when the model changes without replacing hardware.
  • Custom precision: Implement 4-bit or 8-bit arithmetic to balance accuracy and resource usage.
  • Real-world example: Microsoft Project Brainwave deploys FPGAs in Azure data centers for DNN inference.

Neuromorphic Computing

Neuromorphic chips model the brain's neuron–synapse architecture directly in silicon.

  • Intel Loihi 2: Implements Spiking Neural Networks (SNNs) with on-chip learning.
  • IBM TrueNorth: 1 million neurons and 256 million synapses on a single chip with milliwatt power consumption.
  • Event-driven, asynchronous computation enables ultra-low power operation — a compelling advantage for always-on edge AI.

13. Learning Roadmap

[Foundations]
  Boolean AlgebraLogic GatesKarnaugh Maps
[Combinational Circuits]
  Adders, MUX, Decoder, Encoder
[Sequential Circuits]
  LatchesFlip-FlopsRegistersCounters
[System-Level Design]
  FSMDatapathControl Unit
[HDL and FPGA]
  VerilogSimulationFPGA Implementation
[Processor Architecture]
  ALUPipeliningMemory Hierarchy
[AI Hardware]
  GPU ArchitectureTPU/NPUFPGA Acceleration

Quiz

Q1. Why is NAND called a universal gate?

Answer: Because NAND alone can implement NOT, AND, and OR, making it possible to build any Boolean function from NAND gates only.

Explanation:

  • NOT A = A NAND A
  • A AND B = (A NAND B) NAND (A NAND B)
  • A OR B = (A NAND A) NAND (B NAND B)

Since NOT, AND, and OR form a functionally complete set, any logic circuit can be realized with NAND gates exclusively. NOR gates share the same property.

Q2. What is the most negative value representable in 8-bit two's complement, and why is the range asymmetric?

Answer: -128 (binary: 10000000). The range -128 to +127 is asymmetric because zero is treated as positive, consuming one code from the positive half.

Explanation: With 8 bits there are 256 possible patterns. One pattern (00000000) represents zero. The two's complement of 10000000 would require 9 bits to represent as +128, so 10000000 maps exclusively to -128. This asymmetry is an inherent property of two's complement representation.

Q3. What is the key difference between a D latch and a D flip-flop?

Answer: A D latch is level-triggered — it passes D to Q continuously while Enable is HIGH. A D flip-flop is edge-triggered — it samples D only at the clock edge and holds the value until the next edge.

Explanation: Level-triggered behavior makes latches difficult to use in synchronous designs because the output can change multiple times while the enable is asserted. Edge-triggered flip-flops provide strict single-update-per-cycle timing, which is the foundation of clocked synchronous design methodology.

Q4. What is a Don't-care condition in a Karnaugh map and when is it used?

Answer: A Don't-care (X) is an input combination that either cannot occur or whose output value is irrelevant to the system. The designer may assign it 0 or 1 to maximize grouping and minimize the final expression.

Explanation: For example, in a circuit that processes BCD digits (0–9), input combinations 1010 through 1111 (10–15) never appear during normal operation. Marking these six minterms as Don't-cares allows larger groups in the K-map, reducing the number of gates required.

Q5. What is a data hazard in a pipelined CPU, and what are the main techniques to handle it?

Answer: A data hazard occurs when an instruction needs a value that has not yet been written back by an earlier instruction still in the pipeline (a Read-After-Write dependency).

Resolution techniques:

  • Forwarding (Bypassing): Wire the ALU output directly to the next instruction's ALU input, skipping the register file write-back. Resolves most RAW hazards without stalling.
  • Stalling (Pipeline bubble): Insert no-operation cycles until the dependent value is available. Simple but reduces throughput.
  • Compiler scheduling: Reorder independent instructions to fill the slots between a producer and its consumer, avoiding stalls without hardware forwarding.

References