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
+78
View File
@@ -0,0 +1,78 @@
# 마이컴 설계
## 어셈블리 언어
```asm
LOAD 10 ; R0 = 5
LOOP:
LED_ON ; LED 켜기
DELAY 1000 ; 대기
LED_OFF ; LED 끄기
DELAY 1000 ; 대기
DEC ; R0 = R0 - 1
JNZ LOOP ; R0 != 0이면 LOOP로 이동
JZ END_ON ; R0 == 0이면 END_ON으로 이동
END_ON:
LED_ON ; LED 켠 상태 유지
JMP END_ON ; 무한 반복
```
## CPU 구성
CPU 내부의 구성은 다음과 같다.
* PC
* ROM
* Decoder
* GPIO
* Delay Counter
* R0
## 명령어
0x1 LOAD n <br>
0x2 INC <br>
0x3 DEC<br>
0x4 JMP addr<br>
0x5 JZ addr<br>
0x6 JNZ addr<br>
0x7 LED_ON<br>
0x8 LED_OFF<br>
0x9 DELAY n<br>
## 컴파일러
어셉블리로 작성된 프로그램을 명령어 코드로 변환된 기계어 언어로 변환해주는 프로그램
```bash
python asmtohex.py led.asm
```
## 프로그램 다운로드
시리얼을 통해서 기계어 hex 파일로 변환된 프로그램을 다운로드 한다.
```
python hexsend.py led.hex
```
+49
View File
@@ -0,0 +1,49 @@
# 명령어 만들기
TINY CPU MICOM을 이용한 LED 를 제어에 필요한 명령어 SET 구성을 한다.
## LED 켜는 명령어
LED를 제어하는데 필요한 어셈블리 언어에 필요한 명령어들어 16bit 단위로 동작하도록 작성한다.
### 명령어 포맷
16bit = opcode[15:12] + operand[11:0]
### 명령어
| Mnemonic | Operand | Opcode (Hex) | Description |
|-----------|---------|--------------|-------------|
| NOP | - | 0x0 | No Operation |
| LOAD | n | 0x1 | Load immediate value into register |
| INC | - | 0x2 | Increment register |
| DEC | - | 0x3 | Decrement register |
| JMP | addr | 0x4 | Unconditional jump |
| JZ | addr | 0x5 | Jump if zero |
| JNZ | addr | 0x6 | Jump if not zero |
| LED_ON | - | 0x7 | Turn LED on |
| LED_OFF | - | 0x8 | Turn LED off |
| DELAY | n | 0x9 | Delay for n time units |
만약 16비트 명령어 형식(상위 4비트 Opcode, 하위 12비트 Operand)을 사용한다면 다음과 같이 정리할 수도 있습니다.
| Opcode | Mnemonic | Format | Example |
|---------|----------|--------------|---------|
| 0x0 | NOP | NOP | 0x0000 |
| 0x1 | LOAD | LOAD n | 0x100A |
| 0x2 | INC | INC | 0x2000 |
| 0x3 | DEC | DEC | 0x3000 |
| 0x4 | JMP | JMP addr | 0x4005 |
| 0x5 | JZ | JZ addr | 0x500A |
| 0x6 | JNZ | JNZ addr | 0x6002 |
| 0x7 | LED_ON | LED_ON | 0x7000 |
| 0x8 | LED_OFF | LED_OFF | 0x8000 |
| 0x9 | DELAY | DELAY n | 0x93E8 |
@@ -0,0 +1,85 @@
# 어셈블러작성
## LED 프로그램작성
LED 를 제어하는 데 필요한 명령어를 구성을 한다.
### C 언어 표현
C 언어로 작성된 프로그램은 다음과 같이 동작하는 프로그램
```c
#include <stdint.h>
void LED_ON(void);
void LED_OFF(void);
void DELAY(uint32_t ms);
int main(void)
{
int R0;
R0 = 10;
LOOP:
LED_ON();
DELAY(1000);
LED_OFF();
DELAY(1000);
R0--;
if (R0 != 0)
goto LOOP;
END_ON:
LED_ON();
while (1)
{
// JMP END_ON
}
return 0;
}
```
### ASM 언어 표현
- [led.asm 다운로드](files/led.asm)
```asm
LOAD 10 ; R0 = 5
LOOP:
LED_ON ; LED 켜기
DELAY 1000 ; 대기
LED_OFF ; LED 끄기
DELAY 1000 ; 대기
DEC ; R0 = R0 - 1
JNZ LOOP ; R0 != 0이면 LOOP로 이동
JZ END_ON ; R0 == 0이면 END_ON으로 이동
END_ON:
LED_ON ; LED 켠 상태 유지
JMP END_ON ; 무한 반복
```
@@ -0,0 +1,169 @@
# 컴파일러작성
어셈블리 언어를 기계어 hex 파일로 변환한다.
## 변환 프로그램 구동
```bash
python asmtohex.py led.asm
```
- [led.asm 다운로드](files/led.asm)
- [led.hex 다운로드](files/led.hex)
![내 사진](imgs/asmtohex.png)
## 변환프로그램
asmtohex.py 파일 이름으로 다음과 파이썬 언어로 작성한다.
- [asmtohex.py 다운로드](files/asmtohex.py)
```python
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()
```
@@ -0,0 +1,111 @@
# 다운로더 작성
기계어 hex 파일로 FPGA 코어로 전송한다.
## 변환 프로그램 구동
```bash
python hexsend.py led.hex
```
![내 사진](imgs/asmtohex.png)
## 변환프로그램
hexsend.py 파일 이름으로 다음과 파이썬 언어로 작성한다.
[hexsend.py 다운로드](files/hexsend.py)
```python
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()
```
+417
View File
@@ -0,0 +1,417 @@
# FPGA제작
어셈블리에서 hex 기계어로 변환된 코드를 시리얼로 부터 받아서, 구동하는 프로그램을 VHDL로 작성을 한다.
지금까지 만든 CPU를 이용한다면 구조는 다음과 같습니다.
hex 1차 다운로드 → FF FF → 자동 실행
실행 중 새 hexsend.py 전송
→ 첫 바이트 수신 순간 CPU 정지
→ RAM 주소 0부터 다시 저장
→ FF FF 수신
→ 새 프로그램 자동 실행
## 동작과정 설명
## CPU 구성 블록 설명
| 구성요소 | 역할 | 저장 데이터 | 주요 동작 |
| -------------------- | ---------------- | --------------- | ------------------- |
| PC (Program Counter) | 현재 실행할 명령어 주소 저장 | 명령어 주소 | 다음 명령어 위치 관리 |
| Program RAM | 프로그램 저장 | 기계어(16비트 명령어) | UART로 다운로드된 프로그램 저장 |
| Instruction Decoder | 명령어 해석 | Opcode, Operand | 명령어 종류 판별 |
| R0 Register | 범용 레지스터 | 연산 데이터 | LOAD, INC, DEC 수행 |
| Delay Block | 시간 지연 | Delay Counter | 지정 시간 동안 대기 |
| GPIO | 외부 핀 제어 | LED 상태 | LED ON/OFF |
| UART RX | 프로그램 다운로드 | 수신 데이터 | PC로부터 프로그램 수신 |
| Boot Loader | 프로그램 적재 제어 | RAM 주소 | RAM 저장 및 실행 시작 |
즉 현재 설계는 **UART Bootloader + Program RAM + Tiny CPU** 구조로, Quartus 재합성 없이 `ASM → HEX → UART 다운로드 → 즉시 실행`이 가능한 간단한 MCU 형태입니다.
## 동작 시나리오
```
전원인가
│
▼
CPU_LOAD_PROGRAM
│
UART 프로그램 수신
│
FF FF 수신
│
▼
CPU_FETCH
│
▼
CPU_DECODE
│
▼
CPU_DELAY
│
└───────┐
│
▼
CPU_FETCH
실행 중 UART 데이터 수신
│
▼
CPU_LOAD_PROGRAM
│
새 프로그램 수신
│
FF FF
│
▼
새 프로그램 실행
```
---
## 핀테이블
아래와 같이, VHDL에 사용되는 핀을 대한 할당을 한다.
![내 사진](imgs/pintable.png)
---
## VHDL CODE
[micom.vhdl 다운로드](files/micom.vhdl)
```
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;
```
@@ -0,0 +1,66 @@
# 프로그램 실습
1. 어셈블리 언어로 프로그램을 작성하고
2. 컴파일 하고
3. hex 파일을 다운로드
4. FPGA 실습키트에서 동작을 확인한다.
5. VHDL을 매번 수정,컴파일,다운로드하지 않아도, 프로그램 코드를 변경하여 원하는동작을 바로 실행할 수 있다.
## 프로그램 작성
![내 사진](imgs/asm.png)
R0 의 값을 변경하거나, DELAY 의 값을 변경하여 프로그램을 수정한다.
R0 는 LED가 깜빡이는 횟수를 설정하는 것이며, DELAY 에 설정되는 값은 ms의 값으로 지연값을 나타낸다.
## 프로그램 컴파일
```bash
python asmtohex.py led.asm
```
![내 사진](imgs/asmtohex.png)
led.hex 파일을 출력한다.
## 프로그램 전송
hexsend.py 을 이용해서 프로그램을 FPGA 로 동작코드를 전송한다.
```bash
python hexsend.py led.hex
```
![내 사진](imgs/hexsend.png)
## 동작상태 확인
프로그램을 수정하여 컴파일 하여 전송하므로써, 속도, 횟수를 자유롭게 변경하여 프로그램 적용하여 구동할 수 있다.
프로그램을 다운로드 하여 즉시 반영된 동작을 확인한다.
![내 사진](imgs/ledonoff.png)
+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: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB