firstcommit

This commit is contained in:
rco
2026-06-09 21:42:12 +09:00
commit efaf6574f4
198 changed files with 35006 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
# FPGA 모델기반설계
MATLAB/Simulink + HDL Coder를 사용하면 블록 다이어그램으로 설계한 후 자동으로 VHDL 또는 Verilog 코드를 생성할 수 있습니다.
이 과정을 수행하여, 모델기반 설계에 대한 실습을 진행한다.
여기서는 간단한 LED 제어를 위한 모델 기반 설계를 전체 과정을 수행하여, 전체 제작에 대한 이해를 지원한다.
### 주요흐름
```
Simulink 모델 작성
↓
HDL Coder 설정
↓
고정소수점(Fixed Point) 변환
↓
HDL Workflow Advisor 실행
↓
VHDL 생성
↓
Quartus/Vivado 합성
↓
FPGA 다운로드
```
## 응용 예제
FPGA 개발자들이 가장 많이 사용하는 자동 HDL 생성 예제는 다음과 같은 것이 있다.
- UART TX/RX
- FIR Filter
- FFT
- PID Controller
- Motor Control
- PWM Generator
- CNN AI Accelerator
- Ethernet MAC
- Video Processing Pipeline
+133
View File
@@ -0,0 +1,133 @@
# 기능정의
## 동작 정의
키를 입력하면 해당하는 동작을 하도록 한다.
---
![내 사진](imgs/key4.png)
---
| KEY 입력 | LED 동작 |
| --------- | -------- |
| KEY0 = 1 | LED OFF |
| KEY1 = 1 | 느리게 깜빡임 |
| KEY2 = 1 | 보통 속도 |
| KEY3 = 1 | 빠르게 깜빡임 |
| 아무 KEY 없음 | 이전 상태 유지 |
핵심은 LED 상태를 바로 결정하는 것이 아니라, 현재 동작 모드를 레지스터에 저장하는 것입니다.
```
KEY 입력
↓
동작 모드 저장 레지스터
↓
Blink 속도 선택
↓
Counter
↓
LED 출력
```
---
![내 사진](imgs/ledonoff.png)
---
## 모드값 정의
모드에 따른 속도 정의
```
MODE_OFF = 0
MODE_SLOW = 1
MODE_NORMAL = 2
MODE_FAST = 3
```
## KEY 처리 논리
```
if KEY0 = 1
mode = OFF
elseif KEY1 = 1
mode = SLOW
elseif KEY2 = 1
mode = NORMAL
elseif KEY3 = 1
mode = FAST
else
mode = mode 유지
end
```
## Simulink 블록 구성
```
KEY0 ─┐
KEY1 ─┤
KEY2 ─┤→ Mode Select Logic → Unit Delay → mode
KEY3 ─┘
mode → Period Select → Counter → Compare → LED
```
## MTLAB BLOCK 작성
필요한 블록은 직접 MATLAB 코드 블록으로 작성하여 추가하도록 한다.
```
+---------+
| KEY[3:0]|
+---------+
|
v
+----------------+
| MATLAB Function|
| key_led_blink |
+----------------+
|
v
+---------+
| LED |
+---------+
```
## Simulink 입출력
```
입력:
key[4] : Boolean 또는 uint8 벡터
출력:
led : Boolean
```
## VHDL 코드 생성
```
entity key_led_blink is
port(
clk : in std_logic;
reset : in std_logic;
key : in std_logic_vector(3 downto 0);
led : out std_logic
);
end entity;
```
+113
View File
@@ -0,0 +1,113 @@
# 시뮬링크작성
## 기본블록 구성
MATLAB FUNC 블록 코드들 다음과 같이 작성한다.
![내그림](imgs/sim_blk.png)
## MATLAB FUN 블록 작성
MATLAB FUNC 블록을 더블 클릭다여 아래 코드를 작성한다.
---
![내그림](imgs/code.png)
---
```c
function led = fcn(key0, key1, key2, key3)
%#codegen
persistent mode;
persistent cnt;
persistent led_state;
if isempty(mode)
mode = uint8(0); % 0 = OFF
end
if isempty(cnt)
cnt = uint32(0);
end
if isempty(led_state)
led_state = false;
end
% -----------------------------
% 1. KEY 입력에 따라 모드 저장
% -----------------------------
if key0
mode = uint8(0); % OFF
elseif key1
mode = uint8(1); % SLOW
elseif key2
mode = uint8(2); % NORMAL
elseif key3
mode = uint8(3); % FAST
end
% -----------------------------
% 2. 모드에 따라 깜빡임 주기 선택
% 50MHz 클럭 기준
% -----------------------------
period = uint32(0);
if mode == uint8(0)
period = uint32(0); % OFF
elseif mode == uint8(1)
period = uint32(50000000); % 느림
elseif mode == uint8(2)
period = uint32(25000000); % 보통
else
period = uint32(5000000); % 빠름
end
% -----------------------------
% 3. LED 출력 생성
% -----------------------------
if mode == uint8(0)
led_state = false;
cnt = uint32(0);
else
if cnt >= period
cnt = uint32(0);
led_state = ~led_state; % LED 반전
else
cnt = cnt + uint32(1);
end
end
led = led_state;
end
```
## 블록작성완료
선으로 연결하여, 최종 블록 작성을 완료한다. Key 입력이 되도록 블록을 그려준다.
![내그림](imgs/sim_blk_2.png)
---
+145
View File
@@ -0,0 +1,145 @@
# VHDL 코드
HDL Coder 을 이용하여 VHDL 코드를 생성한다.
## 생성된 코드
```
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity led_blink is
port(
clk : in std_logic;
rst : in std_logic;
key0 : in std_logic;
key1 : in std_logic;
key2 : in std_logic;
key3 : in std_logic;
led : out std_logic
);
end entity;
architecture rtl of led_blink is
signal mode : unsigned(1 downto 0) := "00";
signal cnt : unsigned(31 downto 0) := (others=>'0');
signal period : unsigned(31 downto 0);
signal led_state : std_logic := '0';
begin
------------------------------------------------------------------
-- period 결정
------------------------------------------------------------------
process(mode)
begin
case mode is
when "00" =>
period <= to_unsigned(0,32);
when "01" =>
period <= to_unsigned(50000000,32);
when "10" =>
period <= to_unsigned(25000000,32);
when others =>
period <= to_unsigned(5000000,32);
end case;
end process;
------------------------------------------------------------------
-- 메인 상태기계
------------------------------------------------------------------
process(clk,rst)
begin
if rst='1' then
mode <= "00";
cnt <= (others=>'0');
led_state <= '0';
elsif rising_edge(clk) then
----------------------------------------------------------
-- mode 저장
----------------------------------------------------------
if key0='1' then
mode <= "00";
elsif key1='1' then
mode <= "01";
elsif key2='1' then
mode <= "10";
elsif key3='1' then
mode <= "11";
end if;
----------------------------------------------------------
-- LED 생성
----------------------------------------------------------
if mode = "00" then
cnt <= (others=>'0');
led_state <= '0';
else
if cnt >= period then
cnt <= (others=>'0');
led_state <= not led_state;
else
cnt <= cnt + 1;
end if;
end if;
end if;
end process;
led <= led_state;
end architecture;
```
## 핀배치
| 핀 번호 | 신호 |
|---------|------|
| PIN_T2 | clk |
| PIN_E4 | rst |
| PIN_A3 | key0 |
| PIN_A5 | key1 |
| PIN_A6 | key2 |
| PIN_A20 | key3 |
| PIN_B3 | led |
## 테스트 진행
해당 코드를 Quartus 를 이용하여 컴파일 하고, 동작 과정을 실습한다.
+51
View File
@@ -0,0 +1,51 @@
사용법
1. ASM을 HEX로 변환
python asmtohex.py led.asm
결과:
led.hex
2. HEX를 COM3로 전송
python hexsend.py led.hex
pyserial 설치:
pip install pyserial
명령어 포맷:
16bit = opcode[15:12] + operand[11:0]
명령어:
NOP 0x0
LOAD n 0x1
INC 0x2
DEC 0x3
JMP addr 0x4
JZ addr 0x5
JNZ addr 0x6
LED_ON 0x7
LED_OFF 0x8
DELAY n 0x9
led.asm 변환 결과:
1005
7000
9064
8000
9064
3000
6001
5008
7000
4008
시리얼 전송 바이트:
10 05 70 00 90 64 80 00 90 64 30 00 60 01 50 08 70 00 40 08
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
OPCODE = {
"NOP": 0x0,
"LOAD": 0x1,
"INC": 0x2,
"DEC": 0x3,
"JMP": 0x4,
"JZ": 0x5,
"JNZ": 0x6,
"LED_ON": 0x7,
"LED_OFF": 0x8,
"DELAY": 0x9,
}
def remove_comment(line):
return line.split(";")[0].strip()
def parse_number(text):
text = text.strip()
if text.lower().startswith("0x"):
return int(text, 16)
if text.lower().startswith("0b"):
return int(text, 2)
return int(text, 10)
def assemble(asm_text):
labels = {}
instructions = []
pc = 0
# 1차 패스: 라벨 주소 수집
for raw_line in asm_text.splitlines():
line = remove_comment(raw_line)
if not line:
continue
if line.endswith(":"):
label = line[:-1].strip()
if label in labels:
raise ValueError(f"중복 라벨: {label}")
labels[label] = pc
continue
if ":" in line:
label_part, inst_part = line.split(":", 1)
label = label_part.strip()
inst_line = inst_part.strip()
if label in labels:
raise ValueError(f"중복 라벨: {label}")
labels[label] = pc
if inst_line:
instructions.append(inst_line)
pc += 1
continue
instructions.append(line)
pc += 1
machine = []
# 2차 패스: 명령어 변환
for addr, line in enumerate(instructions):
parts = line.replace(",", " ").split()
if not parts:
continue
mnemonic = parts[0].upper()
if mnemonic not in OPCODE:
raise ValueError(f"{addr}: 알 수 없는 명령어: {mnemonic}")
opcode = OPCODE[mnemonic]
operand = 0
if len(parts) >= 2:
arg = parts[1]
if arg in labels:
operand = labels[arg]
else:
operand = parse_number(arg)
if operand < 0 or operand > 0x0FFF:
raise ValueError(f"{addr}: operand 범위 초과 0~4095: {operand}")
word = (opcode << 12) | (operand & 0x0FFF)
machine.append(word)
return machine, labels, instructions
def main():
if len(sys.argv) != 2:
print("사용법: python asmtohex.py led.asm")
sys.exit(1)
asm_path = Path(sys.argv[1])
if not asm_path.exists():
print(f"파일 없음: {asm_path}")
sys.exit(1)
hex_path = asm_path.with_suffix(".hex")
asm_text = asm_path.read_text(encoding="utf-8")
machine, labels, instructions = assemble(asm_text)
with hex_path.open("w", encoding="utf-8") as f:
for word in machine:
f.write(f"{word:04X}\n")
print("라벨:")
for name, addr in labels.items():
print(f" {name} = {addr}")
print()
print("기계어:")
for addr, word in enumerate(machine):
print(f" {addr:02d}: {word:04X} ; {instructions[addr]}")
print()
print(f"HEX 생성 완료: {hex_path}")
if __name__ == "__main__":
main()
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
import sys
import time
from pathlib import Path
try:
import serial
except ImportError:
print("pyserial이 필요합니다.")
print("설치: pip install pyserial")
sys.exit(1)
PORT = "COM3"
BAUD = 115200
def read_hex_file(hex_path):
data = bytearray()
for line_no, raw_line in enumerate(hex_path.read_text(encoding="utf-8").splitlines(), start=1):
line = raw_line.split(";")[0].strip()
if not line:
continue
line = line.replace("0x", "").replace("0X", "")
if len(line) != 4:
raise ValueError(f"{line_no}번째 줄 오류: 16비트 HEX 4자리여야 함: {raw_line}")
word = int(line, 16)
high = (word >> 8) & 0xFF
low = word & 0xFF
data.append(high)
data.append(low)
return data
def main():
if len(sys.argv) != 2:
print("사용법: python hexsend.py led.hex")
sys.exit(1)
hex_path = Path(sys.argv[1])
if not hex_path.exists():
print(f"파일 없음: {hex_path}")
sys.exit(1)
send_data = read_hex_file(hex_path)
send_data.append(0xFF)
send_data.append(0xFF)
print(f"파일: {hex_path}")
print(f"전송 바이트 수: {len(send_data)}")
print("전송 데이터:")
print(send_data.hex(" ").upper())
ser = serial.Serial(
port=PORT,
baudrate=BAUD,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1
)
time.sleep(2)
ser.reset_input_buffer()
ser.reset_output_buffer()
ser.write(send_data)
ser.flush()
ser.close()
print()
print(f"{PORT}, {BAUD}bps 전송 완료")
if __name__ == "__main__":
main()
+18
View File
@@ -0,0 +1,18 @@
LOAD 1 ; R0 = 5
LOOP:
LED_ON ; LED 켜기
DELAY 300 ; 대기
LED_OFF ; LED 끄기
DELAY 300 ; 대기
DEC ; R0 = R0 - 1
JNZ LOOP ; R0 != 0이면 LOOP로 이동
JZ END_ON ; R0 == 0이면 END_ON으로 이동
END_ON:
LED_ON ; LED 켠 상태 유지
JMP END_ON ; 무한 반복
+10
View File
@@ -0,0 +1,10 @@
1001
7000
912C
8000
912C
3000
6001
5008
7000
4008
+315
View File
@@ -0,0 +1,315 @@
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity micom is
port (
clk : in std_logic; -- 50MHz
reset : in std_logic; -- High reset
uart_rx : in std_logic;
led : out std_logic
);
end entity;
architecture rtl of micom is
constant CLK_FREQ : integer := 50000000;
constant BAUD_RATE : integer := 115200;
constant BAUD_CNT : integer := CLK_FREQ / BAUD_RATE;
type ram_type is array (0 to 255) of std_logic_vector(15 downto 0);
signal prog_ram : ram_type := (others => x"0000");
type uart_state_type is (
UART_IDLE,
UART_START,
UART_DATA,
UART_STOP
);
signal uart_state : uart_state_type := UART_IDLE;
signal baud_counter : integer range 0 to BAUD_CNT := 0;
signal bit_index : integer range 0 to 7 := 0;
signal rx_shift : std_logic_vector(7 downto 0) := (others => '0');
signal rx_byte : std_logic_vector(7 downto 0) := (others => '0');
signal rx_valid : std_logic := '0';
signal byte_high : std_logic_vector(7 downto 0) := (others => '0');
signal rx_phase : std_logic := '0';
signal wr_addr : integer range 0 to 255 := 0;
signal cpu_run : std_logic := '0';
type cpu_state_type is (
CPU_LOAD_PROGRAM,
CPU_FETCH,
CPU_DECODE,
CPU_DELAY
);
signal cpu_state : cpu_state_type := CPU_LOAD_PROGRAM;
signal pc : integer range 0 to 255 := 0;
signal inst : std_logic_vector(15 downto 0) := x"0000";
signal opcode : std_logic_vector(3 downto 0);
signal operand : unsigned(11 downto 0);
signal r0 : unsigned(15 downto 0) := (others => '0');
signal zflag : std_logic := '0';
signal delay_counter : unsigned(31 downto 0) := (others => '0');
begin
opcode <= inst(15 downto 12);
operand <= unsigned(inst(11 downto 0));
--------------------------------------------------------------------
-- UART RX
--------------------------------------------------------------------
process(clk, reset)
begin
if reset = '1' then
uart_state <= UART_IDLE;
baud_counter <= 0;
bit_index <= 0;
rx_shift <= (others => '0');
rx_byte <= (others => '0');
rx_valid <= '0';
elsif rising_edge(clk) then
rx_valid <= '0';
case uart_state is
when UART_IDLE =>
if uart_rx = '0' then
baud_counter <= BAUD_CNT / 2;
uart_state <= UART_START;
end if;
when UART_START =>
if baud_counter = 0 then
if uart_rx = '0' then
baud_counter <= BAUD_CNT - 1;
bit_index <= 0;
uart_state <= UART_DATA;
else
uart_state <= UART_IDLE;
end if;
else
baud_counter <= baud_counter - 1;
end if;
when UART_DATA =>
if baud_counter = 0 then
rx_shift(bit_index) <= uart_rx;
baud_counter <= BAUD_CNT - 1;
if bit_index = 7 then
uart_state <= UART_STOP;
else
bit_index <= bit_index + 1;
end if;
else
baud_counter <= baud_counter - 1;
end if;
when UART_STOP =>
if baud_counter = 0 then
rx_byte <= rx_shift;
rx_valid <= '1';
uart_state <= UART_IDLE;
else
baud_counter <= baud_counter - 1;
end if;
end case;
end if;
end process;
--------------------------------------------------------------------
-- Loader
-- 실행 중 새 UART 데이터가 들어오면 자동 초기화 후 재다운로드
--------------------------------------------------------------------
process(clk, reset)
variable word_data : std_logic_vector(15 downto 0);
begin
if reset = '1' then
byte_high <= (others => '0');
rx_phase <= '0';
wr_addr <= 0;
cpu_run <= '0';
elsif rising_edge(clk) then
if rx_valid = '1' then
-- CPU 실행 중 새 데이터가 들어오면 기존 실행 중지 후 재다운로드 시작
if cpu_state /= CPU_LOAD_PROGRAM then
wr_addr <= 0;
rx_phase <= '0';
cpu_run <= '0';
byte_high <= rx_byte;
rx_phase <= '1';
else
if rx_phase = '0' then
byte_high <= rx_byte;
rx_phase <= '1';
else
word_data := byte_high & rx_byte;
if word_data = x"FFFF" then
cpu_run <= '1';
rx_phase <= '0';
else
prog_ram(wr_addr) <= word_data;
if wr_addr < 255 then
wr_addr <= wr_addr + 1;
end if;
rx_phase <= '0';
end if;
end if;
end if;
end if;
end if;
end process;
--------------------------------------------------------------------
-- CPU
--------------------------------------------------------------------
process(clk, reset)
begin
if reset = '1' then
cpu_state <= CPU_LOAD_PROGRAM;
pc <= 0;
inst <= x"0000";
r0 <= (others => '0');
zflag <= '0';
delay_counter <= (others => '0');
led <= '0';
elsif rising_edge(clk) then
-- 실행 중 UART 데이터가 들어오면 CPU를 초기화하고 다운로드 모드로 전환
if rx_valid = '1' and cpu_state /= CPU_LOAD_PROGRAM then
cpu_state <= CPU_LOAD_PROGRAM;
pc <= 0;
inst <= x"0000";
r0 <= (others => '0');
zflag <= '0';
delay_counter <= (others => '0');
led <= '0';
else
case cpu_state is
when CPU_LOAD_PROGRAM =>
if cpu_run = '1' then
pc <= 0;
cpu_state <= CPU_FETCH;
end if;
when CPU_FETCH =>
inst <= prog_ram(pc);
if pc < 255 then
pc <= pc + 1;
end if;
cpu_state <= CPU_DECODE;
when CPU_DECODE =>
case opcode is
when x"0" =>
cpu_state <= CPU_FETCH;
when x"1" =>
r0 <= resize(operand, 16);
if operand = 0 then
zflag <= '1';
else
zflag <= '0';
end if;
cpu_state <= CPU_FETCH;
when x"2" =>
r0 <= r0 + 1;
if r0 + 1 = 0 then
zflag <= '1';
else
zflag <= '0';
end if;
cpu_state <= CPU_FETCH;
when x"3" =>
r0 <= r0 - 1;
if r0 - 1 = 0 then
zflag <= '1';
else
zflag <= '0';
end if;
cpu_state <= CPU_FETCH;
when x"4" =>
pc <= to_integer(operand(7 downto 0));
cpu_state <= CPU_FETCH;
when x"5" =>
if zflag = '1' then
pc <= to_integer(operand(7 downto 0));
end if;
cpu_state <= CPU_FETCH;
when x"6" =>
if zflag = '0' then
pc <= to_integer(operand(7 downto 0));
end if;
cpu_state <= CPU_FETCH;
when x"7" =>
led <= '1';
cpu_state <= CPU_FETCH;
when x"8" =>
led <= '0';
cpu_state <= CPU_FETCH;
when x"9" =>
delay_counter <= to_unsigned(to_integer(operand) * 50000, 32);
cpu_state <= CPU_DELAY;
when others =>
cpu_state <= CPU_FETCH;
end case;
when CPU_DELAY =>
if delay_counter = 0 then
cpu_state <= CPU_FETCH;
else
delay_counter <= delay_counter - 1;
end if;
end case;
end if;
end if;
end process;
end architecture;
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB