feat: 키보드 명령어 처리 기능 추가

- check_input(): 비동기 키보드 입력 (select 사용)
- process_command(): 명령어 처리
- 명령어: c(영점), p(일시정지), r(재시작), h(도움말), q(종료)
This commit is contained in:
2026-01-12 14:46:52 +09:00
parent b2b3cf37fe
commit bc7e52e620

View File

@@ -2,6 +2,11 @@
""" """
LoadCell - Raspberry Pi Python library for HX711 load cell amplifier LoadCell - Raspberry Pi Python library for HX711 load cell amplifier
기능 :
1. 무게 측정 (양수 값으로 출력)
2. 키보드 명령어: 'c' 영점조절, 'p' 일시정지, 'r' 재시작
3. 시작 시 자동 캘리브레이션
하드웨어 연결: 하드웨어 연결:
- HX711 [VCC] -> Pi 5 [Pin 1] (3.3V) - HX711 [VCC] -> Pi 5 [Pin 1] (3.3V)
- HX711 [GND] -> Pi 5 [Pin 6] (GND) - HX711 [GND] -> Pi 5 [Pin 6] (GND)
@@ -11,6 +16,10 @@ LoadCell - Raspberry Pi Python library for HX711 load cell amplifier
from HX711 import SimpleHX711, Rate from HX711 import SimpleHX711, Rate
import time import time
import sys
import select
import tty
import termios
# HX711 핀 설정 # HX711 핀 설정
DT_PIN = 5 # GPIO5 -> 29번 핀 DT_PIN = 5 # GPIO5 -> 29번 핀
@@ -22,6 +31,7 @@ measure_delay = 0.1 # 측정 간격 (초)
density = 1.0 # 기본값: 물 (1.0 g/ml) density = 1.0 # 기본값: 물 (1.0 g/ml)
# 상태 변수 # 상태 변수
is_paused = False
is_calibrated = False is_calibrated = False
offset_value = 0 offset_value = 0
@@ -63,8 +73,6 @@ def perform_calibration():
print("영점 조정 중...") print("영점 조정 중...")
# 10번 읽어서 평균값을 오프셋으로 사용
readings = [] readings = []
for _ in range(10): for _ in range(10):
readings.append(hx.read()) readings.append(hx.read())
@@ -99,33 +107,104 @@ def tare():
def get_weight(): def get_weight():
"""무게 측정 함수""" """무게 측정 함수"""
raw_value = hx.read() raw_value = hx.read()
# (RAW 값 - 오프셋) / 캘리브레이션 팩터 = 무게
weight_g = (raw_value - offset_value) / CALIBRATION_FACTOR weight_g = (raw_value - offset_value) / CALIBRATION_FACTOR
weight_g = max(0, weight_g) # 음수 값 방지
# 밀도 적용 (부피 계산)
volume_ml = weight_g / density volume_ml = weight_g / density
return weight_g, volume_ml return weight_g, volume_ml
def print_help():
"""도움말 출력"""
print()
print("-" * 50)
print("키보드 명령어:")
print(" 'c' : 영점 조절 (Calibration)")
print(" 'p' : 일시정지 (Pause)")
print(" 'r' : 재시작 (Resume)")
print(" 'h' : 도움말 보기")
print(" 'q' : 종료 (Quit)")
print("-" * 50)
print()
def check_input():
"""비동기 키보드 입력 확인"""
if select.select([sys.stdin], [], [], 0)[0]:
return sys.stdin.read(1)
return None
def process_command(cmd):
"""명령어 처리"""
global is_paused
cmd = cmd.lower()
if cmd == 'c':
tare()
elif cmd == 'p':
if not is_paused:
is_paused = True
print("\n>> 측정 일시정지됨")
print(" 'r'을 입력하면 다시 시작합니다.\n")
else:
print("\n>> 이미 일시정지 상태입니다.\n")
elif cmd == 'r':
if is_paused:
is_paused = False
print("\n>> 측정 재시작!\n")
else:
print("\n>> 이미 측정 중입니다.\n")
elif cmd == 'h':
print_help()
elif cmd == 'q':
print("\n>> 프로그램 종료\n")
return False
elif cmd not in ['\n', '\r', ' ']:
print(f">> 알 수 없는 명령어: {cmd}")
print(" 'h'를 입력하면 도움말을 볼 수 있습니다.")
return True
def main(): def main():
if not init_hx711(): if not init_hx711():
return return
perform_calibration() perform_calibration()
print_help()
print("무게 측정 테스트 (10회):") old_settings = termios.tcgetattr(sys.stdin)
print("-" * 50)
for i in range(10): try:
weight_g, volume_ml = get_weight() tty.setcbreak(sys.stdin.fileno())
print(f" [{i+1:2d}] {weight_g:.1f}g / {volume_ml:.1f}ml") print("명령어 테스트 (q: 종료)...\n")
time.sleep(measure_delay)
while True:
cmd = check_input()
if cmd:
if not process_command(cmd):
break
if is_paused:
time.sleep(0.1)
continue
weight_g, volume_ml = get_weight()
print(f"측정: {weight_g:.1f}g / {volume_ml:.1f}ml")
time.sleep(measure_delay)
print("-" * 50) except KeyboardInterrupt:
print("테스트 완료") print("\n>> 프로그램 종료\n")
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
print("프로그램 종료됨.")
if __name__ == "__main__": if __name__ == "__main__":