import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore…
- User
import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import pyqtSlot from PyQt5.QtCore import QThread, pyqtSlot from PyQt5.QtCore import pyqtSignal as Signal from PyQt5 import uic from serial import Serial, SerialException from threading import Thread
Load the UI file using loadUiType
UiClass, BaseClass = uic.loadUiType("C:\Users\zktmt\Desktop\digital_circuit\src\week9\mortor.ui")
class WindowClass(QMainWindow, UiClass): def init(self): super().init() self.setupUi(self) # setupUi method comes from UiClass
self.dev = None self.receiver = Receiver(self) # Connect signals to slots self.pushButton_Open.clicked.connect(self.openFunction) self.pushButton_Clear.clicked.connect(self.clearFunction) self.push_Close.clicked.connect(self.closeFunction) self.pushButton_Set.clicked.connect(self.setFunction) self.pushButton_Reset.clicked.connect(self.resetFunction) self.receiver.rx_data.connect(self.rx_data_append) @pyqtSlot() def clearFunction(self): self.textEdit.clear() @pyqtSlot() def openFunction(self): current_port = self.comboPort.currentText() current_baudrate = int(self.comboBox_Baudrate.currentText()) if self.dev is None or not self.dev.isOpen(): try: self.dev = Serial(current_port, current_baudrate) self.textEdit.append("Device opened") except SerialException as e: self.textEdit.append(f"Failed to open the device: {e}") else: self.textEdit.append("Device already opened") @pyqtSlot() def closeFunction(self): if self.dev: if self.dev.is_open: self.dev.close() self.dev = None self.textEdit.append("Device closed") else: self.textEdit.append("Already closed") else: self.textEdit.append("Already closed") @pyqtSlot() def setFunction(self): current_velocity = int(self.comboBox_Velocity.currentText()) current_direction = (self.comboBox_Direction.currentText()) a=current_direction = (self.comboBox_Direction.currentText()) time_setting=(self.comboBox_Time.currentText()) b=(self.comboBox_Time.currentText()) if current_direction =="정방향": current_direction = int(8) elif current_direction == "역방향": current_direction = int(9) if time_setting =='세팅x': time_setting =int(10) elif time_setting =='5초': time_setting =int(11) elif time_setting =='10초': time_setting =int(12) elif time_setting =='15초': time_setting =int(13) if self.dev: try: sender = Sender(self.dev, current_velocity,current_direction,time_setting) sender.start() self.textEdit.append("SET") self.textEdit.append(f"Velocity:{current_velocity} Direction:{a} Time setting:{b} ") except Exception as e: self.textEdit.append(f"Failed to set: {e}") @pyqtSlot() def resetFunction(self): current_velocity = int(0) current_direction = int(0) time_setting=int(0) if self.dev: try: sender = Sender(self.dev, current_velocity,current_direction,time_setting) sender.start() self.textEdit.append("STOP") except Exception as e: self.textEdit.append(f"Failed to set: {e}") @pyqtSlot(bytes) def rx_data_append(self, r_data): value = int.from_bytes(r_data, byteorder='big', signed=False) # big-endian 처리 if value == 254: self.textEdit.append("작동 중지") # 254를 받으면 "작동 중지" 출력 else: self.textEdit.append(f"Received: {value}") - Assistant
Python PyQt5와
pyserial을 사용하여 주어진 시나리오에 맞게 코드를 수정하기로 하였습니다. 코드에서 시리얼 통신을 통해 정수254를 받을 경우 "작동 중지"라는 텍스트를 출력하도록 하기 위해,Receiver클래스 내의rx_data_append메소드를 약간 조정해야 합니다.현재의
rx_data_append메소드에서는 받은 바이트 데이터를 정수로 변경하고 이를 큰 정수(big-endian)로 해석하여 출력합니다. 이를 조정하여 254 값을 체크하도록 코드를 조금 수정하겠습니다.@pyqtSlot(bytes) def rx_data_append(self, r_data): # big-endian 방식으로 데이터를 정수형으로 변환 value = int.from_bytes(r_data, byteorder='big', signed=False) # 254를 받으면 특별한 메시지 출력 if value == 254: self.textEdit.append("작동 중지") else: self.textEdit.append(f"Received: {value}")위의 코드는 이미 존재하는 로직에서 정확히 필요한 부분만을 조절하여, 254가 들어왔을 때 "작동 중지" 메시지를 내보낼 수 있게 합니다. 기존의 로직에서는
int.from_bytes()를 사용해 바이트를 정수로 변환하고, 이 정수 값이 254일 경우 다른 메시지를 출력하도록 변경하는 접근으로 수정했습니다.마지막으로, 기존 코드에서
Receiver클래스가 시리얼 데이터를 읽고,rx_data시그널을 통해 읽은 데이터를 메인 윈도우 클래스의rx_data_append메소드로 전달하는 방식이 유지되어야 함을 확인합니다. 이를 위한 코드 연결 및 유지 관리가 적절하게 설정되어 있는지 확인하세요. 클래스 초기화 및 메소드 연결이 충분한 코드 주석과 함께 정확히 구현되었는지 확인하는 것이 좋습니다. - User
IndentationError: unindent does not match any outer indentation level PS C:\Users\zktmt\Desktop\digital_circuit\src> 오류가 떠
- Assistant
Python에서
IndentationError는 일반적으로 코드 블록의 들여쓰기가 일관되지 않을 때 발생합니다. Python는 들여쓰기를 매우 엄격하게 다루기 때문에, 코드의 모든 블록이 동일한 수준의 들여쓰기를 사용해야 합니다.오류 메세지에서
unindent does not match any outer indentation level라는 것은, 들여쓰기 레벨이 외부 블록과 일치하지 않는다는 것을 의미합니다. 이것은 아마도 공백과 탭을 혼합해서 사용했거나, 들여쓰기의 깊이가 잘못되었을 가능성이 있습니다.수정하려면, 코드의 들여쓰기를 확인하고 일관된 방식 (공백만 사용하거나 탭만 사용)으로 통일해야 합니다. 일반적으로 Python 커뮤니티에서는 공백 4개를 사용하는 것을 권장합니다.
간단한 예시로, 파이썬에서 아래와 같은 코드는
IndentationError를 유발합니다:def example(): print("Hello") # 이 줄은 def 블록 아래에 있어야 하므로 들여쓰기가 필요올바른 버전은 다음과 같습니다:
def example(): print("Hello")제공하신 코드의 특정 부분을 다시 확인하실 필요가 있습니다. 각 함수나 클래스 시작부분에서 들여쓰기가 일관되게 되어 있는지, 탭 대신 공백을 사용하도록 조정하세요. 코드 편집기의 "탭을 공백으로 변환" 기능을 활용하면 이런 문제를 해결하는 데 도움이 될 수 있습니다.
또한, Python 스크립트를 실행하기 전에, 특히 공개된 플랫폼에서 새로운 환경에서 코드를 실행할 때는 들여쓰기를 다시 한 번 검토하는 것이 좋습니다. 각 IDE나 텍스트 에디터는 들여쓰기를 다루는 방식이 조금씩 다를 수 있으므로, 설정을 잘 확인하셔야 합니다.
- User
- Assistant
- User
- Assistant